ZhongKuo0228 / study

0 stars 0 forks source link

1207. Unique Number of Occurrences #79

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago
  1. 紀錄各 num 出現頻率
  2. 判斷唯一性
class Solution:
    def uniqueOccurrences(self, arr: List[int]) -> bool:
        freq_map, occur_set = {}, set()
        for num in arr:
            freq_map[num] = freq_map.get(num, 0) + 1
        for freq in freq_map.values():
            if freq in occur_set:
                return False
            occur_set.add(freq)
        return True
fockspaces commented 1 year ago

improve: 直接用 set 建構來判斷是否有重複元素

class Solution:
    def uniqueOccurrences(self, arr: List[int]) -> bool:
        freq_map, occur_set = {}, set()
        for num in arr:
            freq_map[num] = freq_map.get(num, 0) + 1
        occur_set = set(freq_map.values())
        return len(occur_set) == len(freq_map.values())