Happiness is more than pleasure without pain

你只有非常努力,才能看起来毫不费力

导航

Lonely Integer

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);
        
    }
}

  

posted on 2015-03-10 18:21  believer  阅读(149)  评论(0)    收藏  举报