首页 > 其他 > 详细

Lonely Integer

时间:2015-03-10 19:13:54      阅读:202      评论:0      收藏:0      [点我收藏+]

There are N integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once.

Sample Input:2

3
1 1 2

Sample Output:2

2

Sample Input:3

5
0 0 1 2 1

Sample Output:3

2
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

public class Solution {
   static int lonelyinteger(int[] a) {
	   HashMap<Integer,Integer> map=new HashMap();
       for(int i=0;i<a.length;i++){
    	
    	   if(map.containsKey(a[i])==false){
    		   map.put(a[i], 1);    		   
    	   }
    	   else
    		   map.put(a[i], 2);     	   
       }
//       for(Map.EntrySet entry : map)
//       {
//       system.out.println(entry.getkey()+ : + entry.getValue());
//       }
       for(Integer i : map.keySet())
       {
       if( map.get(i) ==1)
    	   return i.intValue();
    	   }
//       }
      return 0;
    }
   public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int res;
        
        int _a_size = Integer.parseInt(in.nextLine());
        int[] _a = new int[_a_size];
        int _a_item;
        String next = in.nextLine();
        String[] next_split = next.split(" ");
        
        for(int _a_i = 0; _a_i < _a_size; _a_i++) {
            _a_item = Integer.parseInt(next_split[_a_i]);
            _a[_a_i] = _a_item;
        }
        
        res = lonelyinteger(_a);
        System.out.println(res);
        
    }
}

  

Lonely Integer

原文:http://www.cnblogs.com/gaoxiangde/p/4326724.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!