496.Next Greater Element I
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int n = nums2.length;
int[] ans = new int[nums1.length];
HashMap<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 pos = map.get(nums1[i]);
boolean isFind = false;
for(int j = pos + 1; j < n; j++){
if(nums2[j] > nums1[i]){
isFind = true;
ans[i] = nums2[j];
break;
}
}
if(!isFind)
ans[i] = -1;
}
return ans;
}
}
2-Stack
https://leetcode.com/problems/next-greater-element-i/solution/
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Deque<Integer> stack = new ArrayDeque<>();
Map<Integer, Integer> map = new HashMap<>();
int[] ans = new int[nums1.length];
for(int i = 0; i < nums2.length; i++){
while(!stack.isEmpty() && nums2[i] > stack.peek())
map.put(stack.pop(), nums2[i]);
stack.push(nums2[i]);
}
while(!stack.isEmpty()){
map.put(stack.pop(), -1);
}
for(int i = 0; i < nums1.length; i++){
ans[i] = map.get(nums1[i]);
}
return ans;
}
}