https://leetcode.com/problems/sort-array-by-increasing-frequency/
Sort Array by Increasing Frequency - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
- 반복되는 횟수가 적은 순서대로 정렬
- 횟수가 동일하다면 내림차순 정렬
Example) Input: nums = [1,1,2,2,2,3] Output: [3,1,1,2,2,2]
- 횟수가 동일할 경우 내림차순 정렬이기 때문에 처음에 한 번 내림차순 정렬을 해준다.
- 숫자가 나올 때마다 +1을 해주어 {num:count} 형태로 딕셔너리에 저장한다.
- 딕셔너리를 value 기준으로 정렬해서 정렬한 순서대로 하나씩 꺼낸다.
- 키값을 밸류(횟수)만큼 반복한다.
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
answer = []
nums.sort(reverse=True) # 횟수 같을 때는 내림차순 정렬이니까
freq = collections.defaultdict(int)
for num in nums:
freq[num] += 1
sort = sorted(freq.items(), key=lambda x: x[1], reverse=False) # 밸류 기준 정렬
for item in sort:
answer.extend([item[0]] * item[1])
return answer
'알고리즘' 카테고리의 다른 글
[Python] 리트코드 1567. Maximum Length of Subarray With Positive Product (누적 곱셈) (0) | 2021.10.25 |
---|---|
[Python] 리트코드 463. Island Perimeter (0) | 2021.10.19 |
[Python] 리트코드 695. Max Area of Island (0) | 2021.10.18 |
[Python] 리트코드 1690. Stone Game VII (0) | 2021.10.18 |
[Python] 프로그래머스 문제: 타겟 넘버 (1) | 2021.10.01 |