LeetCode-496. Next Greater Element I

Description

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.

Example 1

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so 
    output -1.

Example 2

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
    For number 2 in the first array, the next greater number for it in the second array is 3.
    For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

Note

1.All elements in nums1 and nums2 are unique.
2.The length of both nums1 and nums2 would not exceed 1000.

Solution 1(C++)

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        stack<int> s;
        unordered_map<int, int> m;
        for (int n : nums) {
            while (s.size() && s.top() < n) {
                m[s.top()] = n;
                s.pop();
            }
            s.push(n);
        }
        vector<int> ans;
        for (int n : findNums) ans.push_back(m.count(n) ? m[n] : -1);
        return ans;
    }
};

算法分析

这道题,我觉得难点有两个:一、理解题目意思;二、如何和stack联系起来。

题目意思解读:findNums数组其实就是Nums的子串。说白了,其实就是要找Num中每个元素右边(后边)第一个比自己大的元素。比如(1,3,4,2),这个数组,对应结果为(1,3)、(3,4)、(4,-1)、(2,-1)。找到这之后,再去看findNums中有那几个元素,然后对应输出就可以了。

如何与stack联系起来?那么就要明白stack能做什么事情。回顾之前学习的数据结构,vector是一种线性结构,可以用来储存具有线性索引关系的数据,map用来快速查找键值对,set用来放置键值对。stack是栈,具有先进后出的特点。这一特点在不同环境可以表现出不同的含义。

我们来分析一下理想的算法,也许就能很好理解解法一的方法了。对于数组中的一个元素n,我们需要看后面的元素中第一个比他大的元素,就是我们要的。要完成这样的操作很简单。假设数组长度为 l ,那么第i个元素后面有l-i个元素,这样一直循环,其复杂度为 l 的平方。

其实我们这里做了很多无用功。对于第i个元素,都要遍历后面所有的元素,来进行大小比较。仔细看一看就能发现,后面的每一个元素都要重复和前面好几个元素分别作比较,如果能同时作比较,那么效率会提高很多。

比如说:[5,6,7,4,8,9,1,2]。对于7,后面是4,目标应该是8。当比较4失败时,其实可以让4去比较,如果4与8比较成功,然后再比较7。其实就是利用暗含的大小关系,因为7与4比较之后,7大于4,如果新的元素比4还小,就不用和7比了,如果比4大,再尝试与7比,自然就会高效很多。

其实分析了这么多,我就是想说,对于新的stack还是要多去从不同角度,不同应用场景去理解这个数据结构,这样才对我熟练运用各种数据结构有好处。

目前对于这道题,我认为可以利用stack储存这种时间先后的关系,推广到先进后出的方法可以用于表达时间回溯的特点。之前做一件事不成功,先存着,尝试做新的事情,新的事情成功了,再去做以前的事情。

程序分析

略。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值