Re: [閒聊] 每日leetcode已回收
看板Marginalman作者JerryChungYC (JerryChung)時間1年前 (2024/07/23 09:06)推噓1(1推 0噓 2→)留言3則, 3人參與討論串545/1548 (看更多)
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])
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.251.52.67 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1721696813.A.13C.html
→
07/23 09:11,
1年前
, 1F
07/23 09:11, 1F
※ 編輯: JerryChungYC (60.251.52.67 臺灣), 07/23/2024 09:12:06
推
07/23 09:17,
1年前
, 2F
07/23 09:17, 2F
→
07/23 09:18,
1年前
, 3F
07/23 09:18, 3F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 545 之 1548 篇):