1. 字典自定義排序
首先按值降序排序,若值相等,則按鍵升序排序。
2. 題解
Python內置函數sorted,然后設定排序規則,對於鍵-x[1],對於值x[0]。
這里輸出的是list,根據需要轉換成dict即可。
nums = sorted(nums_dict.items(), key=lambda x: (-x[1], x[0]))
3. 例題
給定一個字符串數組,再給定整數k,請返回出現次數前k名的字符串和對應的次數。
返回的答案應該按字符串出現頻率由高到低排序。如果不同的字符串有相同出現頻率,按字典序排序。
對於兩個字符串,大小關系取決於兩個字符串從左到右第一個不同字符的 ASCII 值的大小關系。
比如"ah1x"小於"ahb","231"<”32“
字符僅包含數字和字母。
輸入:["a","b","c","b"],2 返回值:[["b","2"],["a","1"]] 說明: "b"出現了2次,記["b","2"],"a"與"c"各出現1次,但是a字典序在c前面,記["a","1"],最后返回[["b","2"],["a","1"]]
4. Code
1 class Solution: 2 def topKstrings(self , strings , k ): 3 res = [] 4 nums_dict = dict() 5 for num in strings: 6 if num not in nums_dict: 7 nums_dict[num] = 1 8 else: 9 nums_dict[num] = nums_dict.get(num) + 1 10 # 先按值降序排序,值相等,按鍵降序排序 11 nums = sorted(nums_dict.items(), key=lambda x: (-x[1], x[0])) 12 i = 0 13 for num in nums: 14 temp = [num[0], str(num[1])] 15 res.append(temp) 16 i += 1 17 if i >= k: 18 break 19 return res 20 21 22 if __name__ == '__main__': 23 nums, k = ["a", "b", "c", "b"], 2 24 print(Solution().topKstrings(nums, k))
5. 結語
努力去愛周圍的每一個人,付出,不一定有收獲,但是不付出就一定沒有收獲! 給街頭賣藝的人零錢,不和深夜還在擺攤的小販討價還價。願我的博客對你有所幫助(*^▽^*)(*^▽^*)!
如果客官喜歡小生的園子,記得關注小生喲,小生會持續更新(#^.^#)(#^.^#)。