-
-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathNextGreaterElement1.java
63 lines (48 loc) · 1.3 KB
/
NextGreaterElement1.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
61
62
63
package leetcode;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* @author nikoo28 on 9/16/17
*/
class NextGreaterElement1 {
private int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> numberNGE = new HashMap<>();
Stack<Integer> numStack = new Stack<>();
for (int i : nums2) {
if (numStack.isEmpty()) {
numStack.push(i);
continue;
}
if (i < numStack.peek()) {
numStack.push(i);
continue;
}
int poppedElement = numStack.peek();
while (poppedElement < i) {
numberNGE.put(poppedElement, i);
numStack.pop();
if (numStack.isEmpty())
break;
poppedElement = numStack.peek();
}
numStack.push(i);
}
while (!numStack.isEmpty()) {
numberNGE.put(numStack.pop(), -1);
}
int[] result = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
result[i] = numberNGE.get(nums1[i]);
}
return result;
}
public static void main(String[] args) {
int[] nums1 = {4, 1, 2};
int[] nums2 = {1, 3, 4, 2};
NextGreaterElement1 nextGreaterElement1 = new NextGreaterElement1();
for (int i : nextGreaterElement1.nextGreaterElement(nums1, nums2)) {
System.out.println(i);
}
}
}