Created
February 9, 2022 17:06
-
-
Save chrisynchen/1d67ab3abcf7d592d28790353c89cf67 to your computer and use it in GitHub Desktop.
Leetcode 496. Next Greater Element I
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int[] nextGreaterElement(int[] nums1, int[] nums2) { | |
Map<Integer, Integer> map = new HashMap<>(); | |
for(int i = 0; i < nums2.length; i++) { | |
map.put(nums2[i], i); | |
} | |
Stack<Integer> stack = new Stack<>(); | |
for(int i = 0; i < nums2.length; i++) { | |
while(!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) { | |
nums2[stack.pop()] = nums2[i]; | |
} | |
stack.push(i); | |
} | |
//we cannot find next greater so set it to -1 | |
while(!stack.isEmpty()) { | |
nums2[stack.pop()] = -1; | |
} | |
for(int i = 0; i < nums1.length; i++) { | |
nums1[i] = nums2[map.get(nums1[i])]; | |
} | |
return nums1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment