Python Dict

Yake1965 2022-01-07 20:20:45 阅读数:436

python dict

136. 只出現一次的數字

Leetcode

class Solution:
def singleNumber(self, nums: List[int]) -> int:
## 方法一:dict 
d = {
}
for i in nums: d[i] = d.get(i, 0) + 1
return [x for x in d if d[x] == 1][0]
## 方法二:Counter
count = Counter(nums)
for i in count:
if count[i] == 1: return i
## 方法五:
return sum(set(nums))*2-sum(nums)

846. 一手順子

Leetcode

class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize: return False
hand.sort()
cnt = Counter(hand)
for h in hand:
if cnt[h] == 0: continue
for num in range(h, h + groupSize):
if cnt[num] == 0: return False
cnt[num] -= 1
return True
版权声明:本文为[Yake1965]所创,转载请带上原文链接,感谢。 https://gsmany.com/2022/01/202201072020447470.html