Skip to content

Commit c5acea2

Browse files
authored
Update Next Greater Element I.java
1 parent cd0ecac commit c5acea2

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed

Easy/Next Greater Element I.java

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
11
class Solution {
22
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
3+
Map<Integer, Integer> map = new HashMap<>();
34
Stack<Integer> stack = new Stack<>();
4-
int[] nextMaximum = new int[nums2.length];
5-
Map<Integer, Integer> indexMap = new HashMap<>();
65
for (int i = nums2.length - 1; i >= 0; i--) {
76
while (!stack.isEmpty() && stack.peek() <= nums2[i]) {
87
stack.pop();
98
}
10-
nextMaximum[i] = stack.isEmpty() ? -1 : stack.peek();
9+
map.put(nums2[i], stack.isEmpty() ? -1 : stack.peek());
1110
stack.push(nums2[i]);
12-
indexMap.put(nums2[i], i);
1311
}
14-
int[] nextMaximumResult = new int[nums1.length];
12+
int[] result = new int[nums1.length];
1513
for (int i = 0; i < nums1.length; i++) {
16-
nextMaximumResult[i] = nextMaximum[indexMap.get(nums1[i])];
14+
result[i] = map.getOrDefault(nums1[i], -1);
1715
}
18-
return nextMaximumResult;
16+
return result;
1917
}
2018
}

0 commit comments

Comments
 (0)