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.
반응형
'python-algorithm' 카테고리의 다른 글
leetcode 1009. Complement of Base 10 Integer (0) | 2023.03.20 |
---|---|
leetcode 2553. Separate the Digits in an Array (0) | 2023.03.14 |
leetcode 2395. Find Subarrays With Equal Sum (0) | 2023.03.13 |
백준 27866 문자와 문자열 (0) | 2023.03.13 |
leetcode 2451. Odd String Difference (0) | 2023.03.08 |
댓글