Single Number(JAVA)

  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?

 

 

 1 public class Solution {

 2     public int singleNumber(int[] A) {

 3        Map<Integer, Integer> map = new HashMap<Integer, Integer>();  

 4      if(A.length == 0 || A == null){  

 5          return 0;  

 6      }  

 7      for(int i=0;i<A.length;i++){  

 8          if(map.containsKey(A[i])){  

 9              int value = map.get(A[i]);  

10              map.put(A[i], value+1);  

11          }else {  

12              map.put(A[i], 1);  

13          }  

14      }  

15      for(int i=0;i<A.length;i++){  

16          int value = map.get(A[i]);  

17          if(value == 1){  

18              return A[i];  

19          }  

20      }  

21      return 0;  

22     }

23 }

  

 

解法2

 

 

异或:相同为0 不同为1

0和a数异或都是a

a和a异或就是0

由于每个数有两个 所以总会相见一次 所以还是0

 

 1 public class singleNumber {

 2 

 3     /**

 4      * @param args

 5      */

 6     public static void main(String[] args) {

 7         int a[]={1,-1,3,3,4,1,5,5,-1,6};

 8         System.out.println(singleNumber(a));

 9 

10     }

11 

12     // 异或

13     public static int singleNumber(int[] A) {

14         int res = 0;

15         for (int i : A) {

16             res ^= i;

17         }

18         return res;

19     }

20     

21 

22 }

 

屌爆

你可能感兴趣的:(number)