求下一个更大的数

来源:互联网 发布:知乎 冯大辉 离职 编辑:程序博客网 时间:2024/04/27 03:10

LeetCode原题:

Next Greater Element II

Description:

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:

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.

Note: The length of given array won’t exceed 10000.

分析:
题目意思是说给定一个数组,并对数组中的每一个元素,找出在此元素后且比它大的第一个元素(如果没找到,就从头开始找,但任在该元素之前),如果没找到,则为-1。

简单的算法:

大多数同学会想到遍历的方法,也就是O(n2)的算法,小编用这个算法提交后,显示有123ms,仅仅高于20%的Java提交者。很明显,第一个想到的方法往往并不是最好的。所以,小编也不推荐这种算法。

推荐的算法:

巧妙利用栈,一次遍历
1. 将数组第一个元素的下标入栈
2. 如果栈顶元素(下标)对应元素>=当前判断的元素,则将此元素的下标入栈,
3. 否则,如果栈不为空且栈顶元素(下标)对应元素<当前元素,则记录下来,并pop栈顶元素。继续此判断过程,结束后,push当前元素。
4. 如果栈中元素不为空,则进行第二次遍历,与第一次遍历过程类似。

这种算法的时间复杂度是O(n),小编用这个算法提交后,显示有50ms,高于70%的Java提交者,效率大大提高。

附Java代码:

class Solution {    public int[] nextGreaterElements(int[] nums) {        if(nums == null)            return null;        if(nums.length <= 0)            return new int[]{};        Stack<Integer> stack = new Stack<>();//存储下标        int[] resInt = new int[nums.length];        stack.push(0);//将第一个元素的下标存入栈        resInt[0] = -1;        for(int i = 1 ; i < nums.length; i ++){            resInt[i] = -1;            if(nums[stack.peek()] >= nums[i])                stack.push(i);//如果栈顶下标对应元素大于或等于当前元素,则将当前元素的下标入栈            else{                while(!stack.isEmpty() && nums[stack.peek()] < nums[i]){                    //否则,如果栈不为空且栈顶下标对应元素小于当前元素,则记录并pop                    resInt[stack.pop()] = nums[i];                }                stack.push(i);            }        }        if(!stack.isEmpty()){            //第二次遍历,清理栈内的元素            for(int i = 0 ; i < nums.length; i ++){                if(nums[stack.peek()] < nums[i]){                    while(!stack.isEmpty() && nums[stack.peek()] < nums[i]){                        //否则,如果栈不为空且栈顶下标对应元素小于当前元素,则记录并pop                        resInt[stack.pop()] = nums[i];                    }                    stack.push(i);                }            }        }        return resInt;    }}
0 0
原创粉丝点击