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?
Subscribe to see which companies asked this question.
/**
* 时间复杂度O(n)
* key:位运算
*/
public class Solution {
public int singleNumber(int[] nums) {
int ones = 0, twos = 0;
for (int i = 0 ;i < nums.length;i++)
{
ones = (ones ^ nums[i]) & (~twos);
twos = (twos ^ nums[i]) & (~ones);
}
return ones;
}
}
解析:
[5,5,5,1],举例假设nums[i] = 5,二进制为nums[i] = 101;
1. 第一次碰到nums[i],ones = nums[i] ; twos = 0 ;
ones = 0, twos = 0;
ones = (ones ^ nums[i]) & (~twos) = ( 000 ^ 101 ) & 111 = 101;
twos = (twos ^ nums[i]) & (~ones) = ( 000 ^ 101 ) & 010 = 0;
2. 第二次碰到nums[i],ones = 0 ; twos = nums[i] ;
ones = 0, twos = nums[i];
ones = (ones ^ nums[i]) & (~twos) = ( 101 ^ 101 ) & 111 = 0;
twos = (twos ^ nums[i]) & (~ones) = ( 000 ^ 101 ) & 111 = 101;
3. 第三次碰到nums[i],ones = 0 ; twos = 0 ;
ones = (ones ^ nums[i]) & (~twos) = ( 000 ^ 101 ) & 010 = 0;
twos = (twos ^ nums[i]) & (~ones) = ( 101 ^ 101) & 111 = 0;