[LeetCode] 103: Single Number II

来源:互联网 发布:布拉格之春 知乎 编辑:程序博客网 时间:2024/06/04 21:13
[Problem]

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?


[Solution]
class Solution {
public:
int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.

// invalid
if(n <= 0)return 0;

int ones = 0, twos = 0, mask = 0;
for(int i = 0; i < n; ++i){
twos |= (ones & A[i]);
ones ^= A[i];
mask = ~(ones & twos);
ones &= mask;
twos &= mask;
}

// the one could occurs one time or two times, but no more than three times
return ones == 0 ? twos : ones;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击