題目:
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
題解:
這題也用位運算,位運算反正我就很糾結很不熟。代碼是網上找的,跟着debug外加別人講才能明白點。
這道題算是single number的變形吧,但是因為是3個相同的數,所以操作並沒那么簡單了。
解題思想是:
把每一位數都想成二進制的數,用一個32位的數組來記錄每一位上面的1的count值。這里注意數組計數是從左往右走,而二進制數數是從右往左的。。所以數組第0位的count就是二進制最低位上的count的。例如:4的二進制是100(當然作為32位就是前面還一堆了000...000100這樣子),3個4的話按照每位相加的話,按照二進制表示法考慮就是300,當然存在數組里面就是003(A[0]=0;A[1]=0;A[2]=3,然后后面到A[31]都得0)。
然后對所有數按照二進制表示按位加好后,就要把他還原成所求的值。這里面的想法是,如果一個數字出現了3次,那么這個數字的每一位上面,如果有1那么累加肯定是得3的,如果是0,自然還是0。所以對每一位取余數,得的余數再拼接起來就是我們要找的那個single one。
這里還原的方法是,對32位數組從0開始,對3取余數,因為數組0位置其實是二進制的最低位,所以每次要向左移。用OR(|)和 + 都可以拼接回來。。
代碼如下:
2 if(A.length == 0||A== null)
3 return 0;
4
5 int[] cnt = new int[32];
6 for( int i = 0; i < A.length; i++){
7 for( int j = 0; j < 32; j++){
8 if( (A[i]>>j & 1) ==1){
9 cnt[j]++;
10 }
11 }
12 }
13 int res = 0;
14 for( int i = 0; i < 32; i++){
15 res += (cnt[i]%3 << i);
16 // res |= (cnt[i]%3 << i);
17 }
18 cnt = null;
19 return res;
20 }
同時還有一種更加看着簡潔的代碼表示,就是按照每一位對所有數字計算count(上面那個是對每一個數計算每一位的count),這樣就可以少用一個循環。。。
代碼如下:
2 int [] count = new int[32];
3 int result = 0;
4 for ( int i = 0; i < 32; i++) {
5 for ( int j = 0; j < A.length; j++) {
6 if (((A[j] >> i) & 1)==1) {
7 count[i]++;
8 }
9 }
10 result |= ((count[i] % 3) << i);
11 }
12 return result;
13 }
Reference:
http://blog.csdn.net/xiaozhuaixifu/article/details/12908869
http://www.acmerblog.com/leetcode-single-number-ii-5394.html