其他分享
首页 > 其他分享> > LeetCode_496 下一个更大元素 1

LeetCode_496 下一个更大元素 1

作者:互联网

1、题目:下一个更大元素 1

给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。

请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。

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

2、解题思路

方法为单调栈加上哈希表。

单调栈实际上就是栈,只是利用了一些巧妙的逻辑,使得每次新元素入栈后,栈内的元素都保持有序(单调递增或单调递减)。

 

其中哈希表中存储的数据为:

hashmap[1] = -1

hashmap[7] = -1

hashmap[4] = 7

hashmap[8] = -1

hashmap[6] = 8

hashmap[3] = 6

hashmap[5] = 6

hashmap[2] = 5

3、代码

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) 
    {
        unordered_map<int,int> hashmap;
        stack<int> st;
        for (int i = nums2.size() - 1; i >= 0; --i) 
        {
            int num = nums2[i]; 
            while (!st.empty() && num >= st.top()) 
            {
                st.pop();
            }
            hashmap[num] = st.empty() ? -1 : st.top();
            st.push(num);
        }

        vector<int> res(nums1.size());
        for (int i = 0; i < nums1.size(); ++i) 
        {
            res[i] = hashmap[nums1[i]];
        }
        return res;
    }
};

标签:hashmap,元素,nums1,vector,496,st,LeetCode,nums2
来源: https://blog.csdn.net/W__winter/article/details/121644124