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?
//java里int始终占4个字节,32位,我们外层循环遍历32次,然后内层循环记录0-31位每一位出现的次数,
//内层循环结束后将结果取余于3即为当前位的值
//时间复杂度O(32 * n), 空间复杂度O(1)
// 比方说
//1101
//1101
//1101
//0011
//0011
//0011
//1010 这个unique的
//----
//4340 1的出现次数
//1010 余3的话 就是那个唯一的数!
public class Solution {
public int singleNumber(int[] A) {
int res=0;
int bit;
for(int j=0;j<32;j++){
bit=0;
for(int i=0;i<A.length;i++){
if((A[i]>>j&1)==1){
bit++;
}
}
bit=bit%3;
res+=(1<<j)*bit;
}
return res;
}
}
浙公网安备 33010602011771号