码迷,mamicode.com
首页 > 其他好文 > 详细

Lonely Integer

时间:2015-03-10 19:14:54      阅读:152      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!