LeetCode503. The next bigger element II

Given a looping array (the next element of the last element is the first element of the array), output the next larger 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:

Input: [1,2,1]
Output: [2,-1,2]
Explanation: The next greater number of the first 1 is 2; the
number 2 cannot find the next greater number; the
second The next largest number of 1 requires a loop search, and the result is also 2.
Note: The length of the input array will not exceed 10,000.

Source: LeetCode
Link: https://leetcode-cn.com/problems/next-greater-element-ii

class Solution {
    
    
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
    
    
        int n=nums.size();
        vector<int> ans;
        for(int i=0;i<n;i++){
    
    
            int tmp=-1;
            for(int j=(i+1)%n,k=0;k<n;(j++)%n,k++){
    
    
                if(nums[j%n]>nums[i]){
    
    
                    tmp=nums[j%n];
                    break;
                }
            }
            ans.push_back(tmp);
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/chaokudeztt/article/details/114444593