[leetcode]: 496. Next Greater Element I

1.题目描述
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
翻译:给两个数组num1,num2(均无重复元素),num1是num2的子集。求:num1中的元素在num2中的位置右边第一个比它大的元素。
例:

Input:
nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
4在第二个数组中找不到比它大的,输出-1
1在第二个数组中,右边第一个比它大的是3
2在第二个数组中,右边没有元素,输出-1

2.分析
我自己的解法复杂度太高,所以参考了solution里面的高票答案。
这里用到了两个数据结构:
map-存储每个元素对应的nextGreater
stack-存储递减序列
步骤:
从左到右遍历数组2:
如果元素X大于当前栈顶,那么栈中所有小于X的元素的nextGreater都是X。把这些元素pop掉。
例如:

数组 [9, 8, 7, 3, 2, 1, 6]
刚开始元素一次入栈 [9, 8, 7, 3, 2, 1]
因为6 > 1 2 3,元素1,2,3的nextGreater都是6,然后pop掉1,2,3

3.代码
c++

vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
    unordered_map<int, int> nextGreater;
    stack<int> s;
    for (int i = 0; i < nums.size(); i++) {
        while (!s.empty() && s.top() < nums[i]) {
            nextGreater[s.top()] = nums[i];
            s.pop();
        }
        s.push(nums[i]);
    }
    vector<int> result;
    for (int i = 0; i < findNums.size(); i++)
        result.push_back(nextGreater.count(findNums[i])?nextGreater[findNums[i]]:-1);
    return result;
}

python

def nextGreaterElement(self, findNums, nums):
    nextGreater={x:-1 for x in nums}
    stack=[]
    for n in nums:
        while len(stack)>0 and stack[-1]<n:
            nextGreater[stack[-1]]=n
            stack.pop()
        stack.append(n)
    return [nextGreater[x] for x in findNums]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值