Description:
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Link:
https://leetcode.com/problems/single-number-ii/#/description
解題方法:
把數組中每個數作為2進制去處理奄喂,那么當把n個數作為2進制放到一起,可以找出規(guī)律媒怯,比如:
...000111000...
...001001000...
...000111000...
...000111000...
由此可以看出規(guī)律推正,當分別記錄數組的所有數在每一位上的總和(即把每一位上的1以10進制的形式相加)只有3種情況:
1觅赊、3a+1
2龙助、3b
3、0
所以只要把數組中的數的二進制每一位的1統(tǒng)計起來康震,然后再%3
燎含,就可以還原特定的那個數(知道特定的數在每一位上是否有1)。
Time Complexity:
O(N)
完整代碼:
int singleNumber(vector<int>& nums)
{
int sum, ans = 0;
for(int i = 0; i < 32; i++)
{
sum = 0;
for(auto a: nums)
{
if((a>>i) & 1)
sum++;
}
if(sum % 3)
ans |= 1<<i;
}
return ans;
}