题目:
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
题意:
给一个数组,在这个数组中除了一个数只出现过1次之外,其他数都出现过3次,要求找到这个只出现过一次的数,要求线性时间复杂度并且要求不另开内存空间。
问题的关键就是设计一种方法可以记录状态,这种状态在出现3次的时候可以恢复如初,借鉴网上大佬的思路,对于每一个32bits的数,我们可以统计每一位上1的个数,假如一个数出现了三次,那么它的二进制位上对应为1的次数也为3的倍数,最后模3,假如不是0,则说明这一位是要找的那一个数的某一位,将这一位记录下来,最后统计相或即可。
代码如下:
class Solution {
public int singleNumber(int[] nums) {
int ans = 0;
for (int i = 0; i < 32; i ++) {
int sum = 0;
for (int j : nums) {
if (((j >> i) & 1) == 1) {
sum ++;
}
}
if (sum % 3 == 1) {
ans |= 1 << i;
}
}
return ans;
}
}
对于 排名第一的那种思路,,,一直不理解,还望大佬讲解。。