1、题目描述
2、思路
暴力法很简单,两层for循环即可。
但是可以使用单调栈来做。解释如图,以高个矮个来比喻。
以上的解释是,从右到左的过程中,如果能找到一个元素比栈顶的元素大,那么依次栈顶的元素比较,直到找到一个比他大的,然后放在他头上。所以单调栈中的元素是一个从左到右的过程中,以最大的元素为底,从栈底到栈顶是一个从大到小的过程。
其实单调栈是一个模版,主要用来解决这种高个矮个的问题,模版如下:
public static int[] nextGreaterElement(int[] nums){
int[] ans = new int[nums.length]; // 存放答案的数组
Stack<Integer> stack = new Stack<>();
for(int i = nums.length - 1; i >= 0 ; i--){ // 倒着往栈里放
while(!stack.isEmpty() && stack.peek() <= nums[i]){
stack.pop(); // 矮个起开,反正也被挡着了。。。
}
ans[i] = stack.isEmpty() ? -1 : stack.peek(); // 这个元素身后的第一个高个
stack.push(nums[i]); // 进队,接受之后的身高判定吧!
}
return ans;
}
3、代码
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] result = new int[nums1.length];
Map<Integer, Integer> map = nextGreater(nums2);
for(int i = 0; i < nums1.length; i++){
result[i] = map.get(nums1[i]);
}
return result;
}
public Map<Integer, Integer> nextGreater(int[] nums){
Map<Integer, Integer> map = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for(int i = nums.length - 1; i >= 0; i--){
while(!stack.isEmpty() && stack.peek() <= nums[i]){
stack.pop();
}
map.put(nums[i], stack.isEmpty() ? -1 : stack.peek());
stack.push(nums[i]);
}
return map;
}
}