LeetCode OJ

 1 /**
 2      * Given an array of integers, every element appears twice except for one. Find that single one.
 3      * 要求最好是时间复杂度为O(n),空间复杂度为O(1)
 4      * 这道题之前在面试的时候,被问到过,思路是借用按位操作符的性质:
 5      * 两个相同的数异或之后为0;那么将数组中所有的数做了异或操作后就是那个出现1次的数
 6      * @param A
 7      * @return
 8      */
 9     public int singleNumber(int[] A){
10         int r = A[0];
11         for(int i=1;i<A.length;i++)
12             r = r^A[i];
13         return r;
14     }
 1 /**
 2      * Given an array of integers, every element appears three times except for one. Find that single one.
 3      * 下面的做法是可以扩展到除了一个数之外,这个数组中所有的数都出现x次的情况下
 4      * @param A
 5      * @return
 6      */
 7     public int singleNumber3(int[] A){
 8         int[] count = new int[32];
 9         int r = 0;
10         for(int i=0;i<32;i++)
11         {
12             count[i] = 0; //初始化
13             for(int j=0;j<A.length;j++)
14             {
15                 int t = (A[j]>>i)&1;
16                 if(t == 1)
17                     count[i]++;
18             }
19             r = r | (count[i]%3<<i);//如果每个数出现x次,则modx
20         }
21         return r;
22     }
有问题可以和我联系,bettyting2010#163 dot com
原文地址:https://www.cnblogs.com/echoht/p/3688390.html