leetcode 1207. 獨一無二的出現次數

在這裏插入圖片描述

不喜歡掉包,我直接先排序,然後計算每個數字出現的次數,沒出現過的次數就加進字典,否則 return False

class Solution:
    def uniqueOccurrences(self, arr: List[int]) -> bool:
        arr.sort()
        length = len(arr)
        if length == 1:
            return True
        last = arr[0]
        cnt = 1
        dic = {}
        for i in range(1, length):
            if arr[i] != last:
                if cnt in dic:
                    return False
                else:
                    dic[cnt] = True
                last = arr[i]
                cnt = 1
            else:
                cnt += 1
        if last == arr[length-1]:
            if cnt in dic:
                return False
            else:
                dic[cnt] = True
        return True

還可以不排序,直接將各個數字出現的次數放到字典中,然後將字典的values()轉換成list
最終返回list的長度是否等於set(list)的長度即可。

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

dict.get(key, default=None)
返回指定鍵的值,如果值不在字典中返回default

key in dict
如果鍵在字典dict裏返回true,否則返回false

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章