※ 引述《JerryChungYC (JerryChung)》之銘言: : https://leetcode.com/problems/sort-array-by-increasing-frequency : 1636. Sort Array by Increasing Frequency : 給一個整數數組 nums ,依照值出現的頻率進行升序排序 : 如果多個值有相同的頻率,則這些值按降序進行排序 : Example 1: : Input: nums = [1,1,2,2,2,3] : Output: [3,1,1,2,2,2] : Example 2: : Input: nums = [2,3,1,3,2] : Output: [1,3,3,2,2] : Explanation: 2跟3的頻率相同,降序為3>2 : Example 3: : Input: nums = [-1,1,-6,4,5,-6,1,4,1] : Output: [5,-1,4,4,-6,-6,1,1,1] : 思路: : 先計算出頻率,排序後再根據次數重複放入 : Python Code: : class Solution: : def frequencySort(self, nums: List[int]) -> List[int]: : result = [] : for key, count in sorted(Counter(nums).items(), key=lambda x: (x[1], -x[0])): : result.extend([key] * count) : return result : 因為相同頻率要降序 所以用(x[1], -x[0]) 思路: 差不多 不過我寫得好醜 有空研究一下Counter好了 感覺很方便 Python Code: class Solution: def frequencySort(self, nums: List[int]) -> List[int]: record = defaultdict(int) for n in nums: record[n] += 1 sorted_pairs = sorted([(x,y) for x,y in record.items()],key = lambda x : (x[1],-x[0])) result = [] while sorted_pairs: x,y = sorted_pairs.pop(0) for _ in range(y): result.append(x) return result -- ※ 發信站: 批踢踢實業坊(ptt-web.org.tw), 來自: 123.194.160.111 (臺灣) ※ 文章網址: https://ptt-web.org.tw/Marginalman/M.1721697536.A.8F1