Skip to content

Commit 1288c32

Browse files
committed
Add solution #870
1 parent 1ab3739 commit 1288c32

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -677,6 +677,7 @@
677677
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
678678
868|[Binary Gap](./0868-binary-gap.js)|Easy|
679679
869|[Reordered Power of 2](./0869-reordered-power-of-2.js)|Medium|
680+
870|[Advantage Shuffle](./0870-advantage-shuffle.js)|Medium|
680681
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|
681682
873|[Length of Longest Fibonacci Subsequence](./0873-length-of-longest-fibonacci-subsequence.js)|Medium|
682683
875|[Koko Eating Bananas](./0875-koko-eating-bananas.js)|Medium|

solutions/0870-advantage-shuffle.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 870. Advantage Shuffle
3+
* https://leetcode.com/problems/advantage-shuffle/
4+
* Difficulty: Medium
5+
*
6+
* You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1
7+
* with respect to nums2 is the number of indices i for which nums1[i] > nums2[i].
8+
*
9+
* Return any permutation of nums1 that maximizes its advantage with respect to nums2.
10+
*/
11+
12+
/**
13+
* @param {number[]} nums1
14+
* @param {number[]} nums2
15+
* @return {number[]}
16+
*/
17+
var advantageCount = function(nums1, nums2) {
18+
const sortedNums1 = [...nums1].sort((a, b) => a - b);
19+
const indexedNums2 = nums2.map((val, idx) => ({ val, idx }))
20+
.sort((a, b) => a.val - b.val);
21+
22+
const result = new Array(nums1.length);
23+
let left = 0;
24+
let right = nums1.length - 1;
25+
26+
for (let i = nums1.length - 1; i >= 0; i--) {
27+
const current = indexedNums2[i];
28+
if (sortedNums1[right] > current.val) {
29+
result[current.idx] = sortedNums1[right--];
30+
} else {
31+
result[current.idx] = sortedNums1[left++];
32+
}
33+
}
34+
35+
return result;
36+
};

0 commit comments

Comments
 (0)