寻找只出现一次的数字

题目要求:Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

方法一 map

 public int singleNumber(int[] A) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        if(A.length==1) return A[0];
        int result = 0;
        for (int i : A)
		{
			if(!map.containsKey(i)) {
				map.put(i, 1);
			}else {
				map.put(i, 2);
			}
		}
       
        for (Map.Entry<Integer,Integer> mEntry : map.entrySet())
		{
		   if(mEntry.getValue()==1) result = mEntry.getKey();
		}
        return result;
    }

方法二 排序

 public int singleNumber(int[] A) {
       Arrays.sort(A);
       int res=0;
       for(int i=0;i<A.length-1;i=i+2) {
    	   if(A[i]!=A[i+1]) {
    		  res= A[i];
    	   }
       }
       return res;
    }

方法三 异或
注意:0和一个数异或,结果为这个数

 public int singleNumber(int[] A) {
        int res =0;        
        for(int i=0;i<A.length;i++) {
        	res^=A[i];
        }
        return res;
    }

你可能感兴趣的:(Java编程)