鏈接: https://oj.leetcode.com/problems/single-number-ii/
雖然知道這個題肯定跟位運算,異或有關...但實在沒想出來怎麼解決
class Solution {
public:
int singleNumber(int A[], int n) {
int l=0,r=1;
sort(A,A+n);
if(n==1)
return A[0];
while(A[l]==A[r])
{
l+=3;
r+=3;
if(r>=n)
break;
}
return A[l];
}
};
後來google了一下
:如果別的數字都出現兩次,那麼解決方法是分別對n個數字異或(見 Single Number)..而異或的實質就是按位模2加,所以,這題的思路就是模擬按位模3加:把出現3次1的位置0,而出現1次1的置1;
該代碼來自網絡:
class Solution {
public:
int singleNumber(int A[], int n) {
int one = 0;
int two = 0;
int three = 0;
for(int i = 0 ; i < n ; i++){
two |= A[i] & one;
one = A[i] ^ one;
three = ~(one&two);
one &= three;
two &= three;
}
return one;
}
};