您的位置:首页 > 其它

[leetcode] Single Number II

2015-06-18 22:28 309 查看
From : https://leetcode.com/problems/single-number-ii/
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 1:

class Solution {
public:
int singleNumber(vector<int> nums) {
int bitnum[32]={0};
int res=0;
for(int i=0; i<32; i++){
for(int j=0, n=nums.size(); j<n; j++){
bitnum[i]+=(nums[j]>>i)&1;
}
res|=(bitnum[i]%3)<<i;
}
return res;
}
};

Solution 2:

class Solution2 {
public:
int singleNumber(vector<int>& nums) {
int ans = 0, posi;
for(int i=0; i<32; i++) {
posi = 0;
for(int j=0, size=nums.size(); j<size; j++) {
posi += (nums[j]>>i)&1;
}
ans |= (posi%3)<<i;
}
return ans;
}
};

public class Solution {
public int singleNumber(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int a = 0;
for(int I=0; I<32; ++I) {
int n = 0;
int F = 1<<I;
for(int i=0; i<nums.length; ++i) {
if((nums[i]&F) != 0) { // 必须不等于0,>0 <0对于正负数的情况会出现错误
++n;
}
}
if(n%3 == 1) {
a |= F;
}
}
return a;
}
}


Solution 3:

class Solution {
public:
int singleNumber(vector<int>& nums) {
// ont %3为1的积累,two %3为2, three %3为0
int one=0, two=0, three=0;
for(int i=0, n=nums.size(); i<n; i++){
// %3为1的积累和这次数的1,即%3为2的积累, 与上次积累%3为2的或为这次积累量
two |= one & nums[i];
// 这次与前一次%3为1的积累异或,为当前%3为1的积累
one ^= nums[i];
// %3为0的积累
three = one & two;
// 将出现三次的置为0
one &= ~three;
two &= ~three;
}
return one;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: