[leetcode javascript]503. 下一个更大元素 II 三种解法

三个方法,先贴代码。

/*用穷举 运行时间320ms*/
var nextGreaterElements = function(nums) {
    let result = [];
    for(let i = 0; i < nums.length; i++){
        let val = nums[i];
        for(let j = 0; j < nums.length; j++){
            if(nums[(i + j) % nums.length] > val){
                result.push(nums[(i + j) % nums.length]);
                break;
            }
        }
        if(result.length != i+1){
            result.push(-1);
        }/*没找到nums[i]的下一个更大的数,对应就是内循环没有push一个数上去。
           即,result的长度 比 此时在nums读到的数的长度 要少一个*/
    }
    return result;
};

单调栈:定义:https://blog.csdn.net/liujian20150808/article/details/50752861

              解法:https://leetcode-cn.com/problems/next-greater-element-ii/solution/dan-diao-zhan-jie-jue-next-greater-number-yi-lei-2/ 

/*运用单调栈 运行时间152ms*/
/*因为弄了两个数组,所以内存消耗较大*/
var nextGreaterElements = function(nums) {
    let result = [],
        s = [],
        len = nums.length;
    
    for(let i = len * 2 - 1; i >= 0; i--){
        while(s.length && s[s.length-1] <= nums[i % len]){
            s.pop();
        }
        result[i % len] = s.length ? s[s.length-1] : -1;
        s.push(nums[i % len]);
    }
    return result;
}

遍历的解法来源:https://leetcode-cn.com/problems/next-greater-element-ii/solution/bian-li-jie-zhu-yi-jing-qiu-chu-de-bu-fen-jie-guo-/

想法很有意思 

/*运用遍历。借助已经求出的部分结果来得出其余结果  运行时间168ms*/
var nextGreaterElements = function(nums) {
    let len = nums.length;
    let result = [];
    
    for(let i = len-1; i >= 0; i--){
        let j = i + 1;
        for(; j < len; j++){
            if(nums[j] > nums[i]){
                result[i] = nums[j];
                break;
            }else{
                if(nums[i] < result[j]){
                    result[i] = result[j];
                    break;
                }
            }
        }

        if(j == len){//当往后往不了的时候就会从头。
            for(j = 0; j < i; j++){/*为什么是i?我一开始是打len...害,如果从头的话,肯定是从0到i啊!
                                     因为i后面的在上一个for循环已经经历过了*/
                if(nums[j] > nums[i]){
                    result[i] = nums[j];
                    break;
                }
            }
            if(j == i)//即,j在从头轮一遍之后,依旧没找到比尾部大的值,返回-1
                result[i] = -1;
        }
    }
    return result;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值