137.single number ii 只出现一次的数字 II
一、刷题内容
原题链接
https://leetcode-cn.com/problems/single-number-ii/
内容描述
给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。
示例 1:
输入:nums = [2,2,3,2]
输出:3
示例 2:
输入:nums = [0,1,0,1,0,1,99]
输出:99
提示:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次
二、解题方案
1.方法一:排序
count函数(计数),index函数(查找序号),sort函数(计数)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
nums.sort()
p=0
while p<len(nums):
if nums.count(nums[p])==1:
return nums[p]
p+=3
2.方法二:Hashset
将输入数组存储到 HashSet,然后使用 HashSet 中数字和的三倍与数组之和比较。
3 × (a + b + c) - ( a + a + a + b + b + b + c) = 2c
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return (3 * sum(set(nums)) - sum(nums)) // 2
3.方法三:count函数
利用集合中元素不重复的性质
class Solution:
def singleNumber(self, nums: List[int]) -> int:
a=set(nums)
for i in a:
if nums.count(i)==1:
return i
4.方法四:HashMap
遍历输入数组,统计每个数字出现的次数,最后返回出现次数为 1 的数字。
from collections import Counter
class Solution:
def singleNumber(self, nums: List[int]) -> int:
hashmap = Counter(nums)
for k in hashmap.keys():
if hashmap[k] == 1:
return k
5.方法五:位运算
思路
仅当 twice 未变时,改变 once。
仅当 once 未变时,改变twice。
class Solution:
def singleNumber(self, nums: List[int]) -> int:
once = twice = 0
for num in nums:
once = ~twice & (once ^ num)
twice = ~once & (twice ^ num)
return once