LeetCode496 -- 下一个更大元素 单调栈

题目描述

给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。

nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。

示例 1:

输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
    对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
    对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
    对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。

解题思路

利用hashmap高效查找。

建立hashmap的过程最简单的就是暴力法 ,时间复杂度是n方。

我们可以使用单调栈优化。单调栈就是栈中元素是单调增或者单调减的,如果当前元素满足使栈顶出栈的条件就出栈,并接着判断新栈顶,如果不满意出栈条件就入栈。同 leetcode接雨水问题。

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        int[] res = new int[len1];
        HashMap map = new HashMap<>(); //查找快速就用hash表
        // 使用单调栈优化建立hashmap的过程
        Stack stack = new Stack<>();
        int i = 0;
        while (i < len2){
            while (!stack.empty() && nums2[i] > stack.peek()){
                map.put(stack.pop(),nums2[i]);
            }
            stack.push(nums2[i]);
            i++;
        }
        while (!stack.empty()){
            map.put(stack.pop(),-1);
        }
        for (int j = 0;j < len1;j++){
            res[j] = map.get(nums1[j]);
        }
        return res;
    }
}

 

你可能感兴趣的:(leetcode)