我是靠谱客的博主 文艺龙猫,这篇文章主要介绍面试题56 - II. 数组中数字出现的次数 II(位操作!!!!)hashmap位操作,现在分享给大家,希望可以做个参考。

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。

hashmap

class Solution:
def singleNumber(self, nums: List[int]) -> int:
dic = {}
for i in nums:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
for i,j in dic.items():
if j == 1:
return i

位操作

class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = 0
for i in range(32):
cnt = 0
# 记录当前 bit 有多少个1
bit = 1 << i
# 记录当前要操作的 bit
for num in nums:
if num & bit != 0:
cnt += 1
if cnt % 3 != 0:
# 不等于0说明唯一出现的数字在这个 bit 上是1
res |= bit
return res - 2 ** 32 if res > 2 ** 31 - 1 else res

最后

以上就是文艺龙猫最近收集整理的关于面试题56 - II. 数组中数字出现的次数 II(位操作!!!!)hashmap位操作的全部内容,更多相关面试题56内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(118)

评论列表共有 0 条评论

立即
投稿
返回
顶部