leetcode 503. Next Greater Element II

题目描述:

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.

思路:

同496 https://blog.csdn.net/orangefly0214/article/details/96742224,以及https://blog.csdn.net/orangefly0214/article/details/96696883

本题唯一的不同是需要从数组中循环获得下一个较大值。

自己想了一种方法,通过拼接的方式构造一个循环数组,为了让数组能够循环,将原数组最后一个元素之前的元素拼接到它的后面,比如[1,2,1],最后拼接成[1,2,1,1,2],然后利用之前496等的方法对这个新数组求下一个较大值。

实现1:(不推荐,时间和空间消耗都高)

import java.util.Stack;
import java.util.HashMap;
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        if(nums.length==0) return new int[0];
        int[] temp=new int[nums.length*2-1];
        int mid=temp.length/2;
        //构造一个循环数组
        for(int i=0;i s=new Stack();
        HashMap map=new HashMap<>();
        for(int i=0;itemp[s.peek()]){
                map.put(s.peek(),temp[i]);
                s.pop();
            }
            s.push(i);            
        }
        int[] ret=new int[nums.length];
        for(int i=0;i

 

实现2:(取余实现数组循环)

利用取余,实现循环,且为了循环,我们的数组长度变化最大应该到2n。

注意:当我们对数组判断到最后一个元素后,元素就不再压栈,因为接下来就是循环之前的元素,这些元素的下一个较大值在之前就已经判断过了。

import java.util.Stack;
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        if(nums.length==0) return new int[0];
        int n=nums.length;
        int[] ret=new int[n];
        Arrays.fill(ret,-1);
        Stack s=new Stack<>();
        for(int i=0;i<2*n;i++){
            int curr=nums[i%n];
            while(!s.isEmpty()&&curr>nums[s.peek()]){
                ret[s.pop()]=curr;
            }
            if(i

 

你可能感兴趣的:(leetcode)