-
Notifications
You must be signed in to change notification settings - Fork 56
/
Solution.java
37 lines (34 loc) · 1.14 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package g0401_0500.s0496_next_greater_element_i;
// #Easy #Array #Hash_Table #Stack #Monotonic_Stack #Programming_Skills_I_Day_5_Function
// #2022_07_21_Time_4_ms_(81.18%)_Space_43.7_MB_(77.46%)
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> indexMap = new HashMap<>();
for (int i = 0; i < nums2.length; i++) {
indexMap.put(nums2[i], i);
}
for (int i = 0; i < nums1.length; i++) {
int num = nums1[i];
int index = indexMap.get(num);
if (index == nums2.length - 1) {
nums1[i] = -1;
} else {
boolean found = false;
while (index < nums2.length) {
if (nums2[index] > num) {
nums1[i] = nums2[index];
found = true;
break;
}
index++;
}
if (!found) {
nums1[i] = -1;
}
}
}
return nums1;
}
}