Next Greater Element I LeetCode solution in JavaScript

1
/**
2
* @param {number[]} nums1
3
* @param {number[]} nums2
4
* @return {number[]}
5
*/
6
var nextGreaterElement = function (nums1, nums2) {
7
// [Value, Index] of all numbers in nums2
8
const indexMap = new Map();
9
for (let i = 0; i < nums2.length; i++) {
10
indexMap.set(nums2[i], i);
11
}
12

13
// Stores the next greatest elements
14
let result = [];
15

16
// Iterate through all the numbers of interest. Remember that all numbers in nums1 are present in nums2.
17
for (let num of nums1) {
18
// Check to see those numbers were present in the nums2 indexMap
19
if (indexMap.has(num)) {
20
// If they were, we must find the next greatest element.
21
// Set it to -1 by default in case we cannot find it.
22
let nextGreatest = -1;
23

24
// Iterate through all numbers in nums2 to the right of the index of the target number. (index of the target + 1)
25
for (let i = indexMap.get(num) + 1; i < nums2.length; i++) {
26
// Check to see if the current number is greater than the target.
27
if (nums2[i] > num) {
28
// If it is, this is the next greatest element.
29
nextGreatest = nums2[i];
30
// Break the loop.
31
break;
32
}
33
}
34
// Add the next greatest element (if found). Otherwise, add -1 (default)
35
result.push(nextGreatest);
36
}
37
}
38

39
// Return the array of next greatest elements.
40
return result;
41
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0