forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_496.java
60 lines (53 loc) · 1.82 KB
/
_496.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.fishercoder.solutions;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Stack;
public class _496 {
public static class Solution1 {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] ans = new int[nums1.length];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums2.length; i++) {
map.put(nums2[i], i);
}
for (int i = 0; i < nums1.length; i++) {
int start = map.get(nums1[i]);
for (int j = start + 1; j < nums2.length; j++) {
if (nums2[j] > nums1[i]) {
ans[i] = nums2[j];
break;
}
}
if (ans[i] == 0) {
ans[i] = -1;
}
}
return ans;
}
}
public static class Solution2 {
/**
* Use monotonic stack, using a pen and paper to help visualize this is a great help!
*/
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Deque<Integer> stack = new LinkedList<>();
Map<Integer, Integer> map = new HashMap();
for (int i = 0; i < nums2.length; i++) {
while (!stack.isEmpty() && nums2[i] > stack.peekLast()) {
map.put(stack.pollLast(), nums2[i]);
}
stack.addLast(nums2[i]);
}
while (!stack.isEmpty()) {
map.put(stack.pollLast(), -1);
}
int[] result = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
result[i] = map.get(nums1[i]);
}
return result;
}
}
}