数组中数字出现的次数2
题目
在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。
1 < = n u m s . l e n g t h < = 10000 , 1 < = n u m s [ i ] < 2 31 1 <= nums.length <= 10000,1 <= nums[i] < 2^{31} 1<=nums.length<=10000,1<=nums[i]<231
思路
哈希
C++哈希表用unordered_map实现,注意pair.first和pair.second
位运算
- 从第 1 位开始
- 创建掩码(当前位为 1,其他为 0),count 设置为 0
- 将每个数字和掩码进行&运算,如果结果不为 0,count 加 1
- 如果 count 整除 3,说明出现一次的数字这一位不是 1;否则,说明出现一次的数字这一位是 1
- 继续检查第 2 位,一直到 32 位,结束
C++ 哈希表
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_map<int, int> hash;
for(int num: nums)
++hash[num];
for(auto pair:hash)
{
if(pair.second==1)
return pair.first;
}
return 0;
}
};
python 位运算
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ans = 0
for i in range(32): #一位一位判断
cnt = 0
for num in nums:
if num & 1 <<i:
cnt += 1
if cnt % 3==1: #出现1次数字的这一位是1
ans ^= (1<<i)
return ans