본문 바로가기
python-algorithm

leetcode 1122. Relative Sort Array

by 무적김두칠 2023. 3. 13.

https://leetcode.com/problems/relative-sort-array/description/

 

Relative Sort Array - LeetCode

Can you solve this real interview question? Relative Sort Array - Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are t

leetcode.com

 

1
2
3
4
5
6
7
8
9
class Solution:
    def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
        c = collections.Counter(arr1)
        answer = []       
        for i in arr2:
            answer +=([i]*c.pop(i))
        return answer + sorted(c.elements())
        
 
cs

arr2 에 있는 값들과 없는 값은 다르게 정렬해줘야하는데

arr2에 있는 경우는 그 값이 arr1에 있는 만큼을 answer list에 넣어주고
없는경우는 counter의 elements 만 정렬해서 넣어주면됨 

The values ​​in arr2 and the values ​​without it should be sorted differently.

If it is in arr2, the value is put in the answer list as much as it is in arr1
If there is none, just sort and insert the elements of the counter.

반응형

댓글