Set Dict

  • 219. 存在重复元素 II
  • 136. 只出现一次的数字
  • 846. 一手顺子


219. 存在重复元素 II

Leetcode

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:        
        n = len(nums)
        # 1、双 for 超时
        # for i in range(n):
        #     for j in range(max(0,i-k),i):
        #         if nums[i] == nums[j]:
        #             return True

        # 2、in
        # for i in range(n):
            # if nums[i] in set(nums[i+1:i+1+k]):return True

        # 3、set
        s, c = set(), 0
        for i, num in enumerate(nums):
            if num in s: return True
            s.add(num)
            # 1) 计数
            # c += 1
            # if c > k:
            #     s.remove(nums[i - k])
            #     c -= 1
            # 2) 计数
            # if c < k: c += 1
            # else: s.remove(nums[i - k])
            # 3) len 
            if len(s) > k: s.remove(nums[i - k])

        return False

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