题目内容
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?
题目分析
给一个数组,数组中的数字只有一个出现了一次,其他都出现了三次。在线性时间内找到这个数字。
可以通过位操作,假设现在有一个32位的数组,将数字转化成二进制数。如果这个数字的二进制位为1,那就在对应的数组上加1。如果这个数出现了三次,那么他的二进制对应位的数字一定是3的倍数。
由于会出现只出现一次的数字的值,在数组上进行累加,所以取模3,就可以得到该数字。
该方法有一定的通解性,如果数字重复出现,5次,7次,效果也是一样的,只是取模的值发生了变化。
public int singleNumber(int[] nums) {
int ans = 0;
for(int i = 0; i < 32; i++) {
int sum = 0;
for(int j = 0; j < nums.length; j++) {
if(((nums[j] >> i) & 1) == 1) {//位操作,取得1-32位对应的值是否为1,然后通过sum++进行判断和取模。
sum++;
sum %= 3;
}
}
if(sum != 0) {
ans |= sum << i;//对答案不断的进行补充还原
}
}
return ans;
}