前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T26-下一个更大元素 II

【leetcode刷题】T26-下一个更大元素 II

作者头像
木又AI帮
修改2019-07-18 09:54:18
4290
修改2019-07-18 09:54:18
举报
文章被收录于专栏:木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.

Example 1:

代码语言:javascript
复制
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2; 
The number 2 can't find next greater number; 
The second 1's next greater number needs to search circularly, which is also 2.

【中文题目】

给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。

示例 1:

代码语言:javascript
复制
输入: [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数; 
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。

【思路】

本题和【T25-下一个更大元素 I】基本类似,可以把数组复制一次,这样数组长度为2n,而只需计算前n个元素的greater number并返回结果即可。

暴力破解,两层循环,时间复杂度O(n^2)

使用栈,循环遍历元素e,当栈为空或者e大于栈顶元素,弹出栈顶元素,否则压栈。(栈始终维持栈顶元素到栈底元素从小到大)

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def nextGreaterElements(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        if len(nums) < :
            return []
        ls = []
        res = [-1] * len(nums)
        # 第一次循环
        for i,n in enumerate(nums):
            while len(ls) >  and nums[ls[-1]] < n:
                res[ls.pop()] = n
            ls.append(i)
        # 第二次循环,不再添加元素  
        for i,n in enumerate(nums):
            while len(ls) >  and nums[ls[-1]] < n:
                res[ls.pop()] = n
        return res

C++版本

代码语言:javascript
复制
class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        // 所有的结果初始化为-1
        vector<int> res(nums.size(), -1);
        if(nums.size() < )
            return res;
        stack<int> ls;
        ls.push();
        // 第一次循环
        for(int i=; i<nums.size(); i++){
            while(ls.size() >  && nums[ls.top()] < nums[i]){
                res[ls.top()] = nums[i];
                ls.pop();
            }
            ls.push(i);
        }

        // 第二次循环,栈不再添加元素  
        for(int i=; i<nums.size(); i++){
            while(ls.size() >  && nums[ls.top()] < nums[i]){
                res[ls.top()] = nums[i];
                ls.pop();
            }
        }
        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-04-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档