Skip to content

Commit cb61eac

Browse files
committedJan 10, 2025
Add solution #1122
1 parent a143b84 commit cb61eac

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,7 @@
278278
1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium|
279279
1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy|
280280
1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy|
281+
1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy|
281282
1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy|
282283
1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy|
283284
1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy|

‎solutions/1122-relative-sort-array.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* 1122. Relative Sort Array
3+
* https://leetcode.com/problems/relative-sort-array/
4+
* Difficulty: Easy
5+
*
6+
* Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all
7+
* elements in arr2 are also in arr1.
8+
*
9+
* Sort the elements of arr1 such that the relative ordering of items in arr1
10+
* are the same as in arr2. Elements that do not appear in arr2 should be
11+
* placed at the end of arr1 in ascending order.
12+
*/
13+
14+
/**
15+
* @param {number[]} arr1
16+
* @param {number[]} arr2
17+
* @return {number[]}
18+
*/
19+
var relativeSortArray = function(arr1, arr2) {
20+
const map = new Map(arr2.map((v, i) => [v, i]));
21+
return arr1.sort((a, b) => (map.get(a) ?? arr2.length + a) - (map.get(b) ?? arr2.length + b));
22+
};

0 commit comments

Comments
 (0)
Please sign in to comment.