Single Number II

該題要求不使用額外的空間,可是個人兩個方法都沒有符合要求: java


1. code

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

public class Solution {
    public int singleNumber(int[] A) {
        Map<Integer, Integer> map = new HashMap<Integer,Integer>();
        
        for(int i=0;i<A.length;++i){
            if(map.containsKey(A[i]) && map.get(A[i]) > 1){
                map.remove(A[i]);
            }else{
                int value = map.get(A[i])==null ? 1 : 2;
                map.put(A[i],value);
            }
        }
        
        return map.entrySet().iterator().next().getKey();
    }
}
相關文章
相關標籤/搜索