관리 메뉴

솜씨좋은장씨

[leetCode] 1636. Sort Array by Increasing Frequency (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 1636. Sort Array by Increasing Frequency (Python)

솜씨좋은장씨 2021. 1. 23. 15:26
728x90
반응형

Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.

Return the sorted array.

 

Example 1:

Input: nums = [1,1,2,2,2,3]
Output: [3,1,1,2,2,2]
Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.

Example 2:

Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.

Example 3:

Input: nums = [-1,1,-6,4,5,-6,1,4,1]
Output: [5,-1,4,4,-6,-6,1,1,1]

Constraints:

  • 1 <= nums.length <= 100
  • -100 <= nums[i] <= 100

Solution

from collections import Counter

class Solution:
    def frequencySort(self, nums: List[int]) -> List[int]:
        cnt = Counter(nums).items()
        
        sorted_list = sorted(cnt, key=lambda x: (x[1], -x[0]))
        
        answer_list = []
        
        for val in sorted_list:
            answer_list = answer_list + [val[0]] * val[1]
            
        return answer_list

Solution 풀이

이 문제는 list안에 존재하는 숫자들의 빈도수, 숫자의 크기(내림차순)를 기준으로 정렬하는 문제입니다.

먼저 collections의 Counter를 활용하여 빈도수를 구하고 구한 다음 sorted를 활용하여 기준대로 정렬합니다.

마지막으로 각 숫자를 다시 빈도수 만큼 다시 list에 넣어 정답을 만들어주면 됩니다.

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments