//Single Number II Total Accepted: 45470 Total Submissions: 131046 My Submissions Question Solution
//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?
解法一:
int 数据共有32位,可以用32变量存储 这 N 个元素中各个二进制位上 1 出现的次数,最后 在进行 模三 操作,如果为1,那说明这一位是要找元素二进制表示中为 1 的那一位。代码如下:
-
class Solution {
-
public:
-
int singleNumber(int A[], int n) {
-
int bitnum[32]={0};
-
int res=0;
-
for(int i=0; i<32; i++){
-
for(int j=0; j
-
bitnum[i]+=(A[j]>>i)&1;
-
}
-
res|=(bitnum[i]%3)<
-
}
-
return res;
-
}
-
};
时间:O(32*N),这是一个通用的解法,如果把出现3次改为 k 次,那么只需模k就行了。
解法二
public class SingleNumberTwo {
public int singleNumber(int[] A) {
int one=0,two=0,three=0;
for(int i=0;i
two|=one&A[i];
one^=A[i];
three=one&two;
one=one&~three;
two=two&~three;
}
return one;
}
}
阅读(368) | 评论(0) | 转发(0) |