LeetCode (503) - the next bigger element II

topic

503. Next greater element II
Given a looping array (the next element of the last element is the first element of the array), output the next greater element of each element. The next larger element of the number x is in the array traversal order. The first number after this number is larger than it, which means you should search for the next larger number in a loop. If it does not exist, -1 is output.

Example 1:

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

Note: The length of the input array will not exceed 10,000.

Problem solution (Java)

class Solution 
{
    
    
    public int[] nextGreaterElements(int[] nums) 
    {
    
    
        //结果数组
        int[] result = new int[nums.length];
        //初始化result数组
        for(int index = 0;index < nums.length;index++)
        {
    
    
            result[index] = -1;
        }
        //遍历nums数组
        for(int index = 0;index < nums.length;index++)
        {
    
    
            int count = index + 1;
            while(count != index)
            {
    
    
                //当count已经是最大值时,再次从0开始
                if(count == nums.length)
                {
    
    
                    count = 0;
                }
                //第一个是最大值的情况
                if(count == index)
                {
    
    
                    break;
                }
                //如果找到更大的数
                if(nums[count] > nums[index])
                {
    
    
                    result[index] = nums[count];
                    break;
                }
                //count向后移动
                count++;
            }
        }
        return result;
    }
}

insufficient

Although it was done, it took too long. No simple method was adopted, which was pure violence.
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_46841376/article/details/114435801