503. Next Greater Element II

来源:互联网 发布:网络运维管理系统 编辑:程序博客网 时间:2024/06/08 05:00

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(n^2),会超时。

为了避免重复工作,我们从后往前遍历,这样前面的数可以利用后面的数的结果。比如nums[i]的第一个比它大的数的下标为k,那么对nums[i-1],如果nums[i-1] < nums[i],那么结果的下标就是i,等于则结果的下标就是k,大于则结果的下标最小是k,直接从k开始找。

代码如下,用时22ms

public class Solution {    public int[] nextGreaterElements(int[] nums) {        int n = nums.length, temp[] = new int[n];//temp记录第一个大的数的下标        for(int i = 0; i < n; i++)  temp[i] = -2;//-2代表未知        //从后往前找,尽量避免重复工作        for(int i = n - 1; i >= 0; i--){            int j = i + 1;            while(j < i + n){                //比nums[i]大,找到                if(nums[j % n] > nums[i]) break;                else{                    //-1说明已经没有比num[j]更大的数,直接跳过所有数                    if(temp[j % n] == -1) j = i + n;                    //-2说明未知,继续下一个数                    else if(temp[j % n] == -2)    j++;                    //直接跳到比nums[j]大的第一个数,再与nums[i]比较                    else j = temp[j % n];                  }            }            temp[i] = (j == i + n ? -1 : j);        }        //得到结果        int[] res = new int[n];        for(int i = 0; i < n; i++){            res[i] = (temp[i] == -1 ? -1 : nums[temp[i] % n]);        }        return res;    }}

解法2

维持一个从栈顶向下从小到大排列的栈来实现,从前向后遍历,每次把所有比当前数num[i]小的数出栈,并设置它们的第一个大的数的下标为i,之后把当前数入栈。

代码如下,用时59 ms

public class Solution {    public int[] nextGreaterElements(int[] nums) {        int n = nums.length, next[] = new int[n];        Arrays.fill(next, -1);        Stack<Integer> stack = new Stack<>(); // index stack        for (int i = 0; i < n * 2; i++) {            int num = nums[i % n];             while (!stack.isEmpty() && nums[stack.peek()] < num)                next[stack.pop()] = num;            if (i < n) stack.push(i);        }           return next;    }}
原创粉丝点击