Header Ad

Leetcode Next Greater Element II problem solution

In this Leetcode Next Greater Element II problem solution Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

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, return -1 for this number.

Leetcode Next Greater Element II problem solution


Problem solution in Python.

class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        output = [-1] * len(nums)
        # print(nums)
        for idx in range(0, len(nums)):
            idx2 = 0 if (idx == len(nums) -1) else idx + 1
            # print ('current Idx', idx, nums[idx])
            while (idx2 != idx):
                if (nums[idx] < nums[idx2]):
                    output[idx] = nums[idx2]
                    idx2 = idx
                    break
                idx2 = 0 if (idx2 == len(nums) -1) else idx2 + 1
        print('output', output)
        return output

Problem solution in Java.

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int arr[] =new int[nums.length];
        boolean b = false;
        for(int i=0;i<nums.length;i++){
            b = false;
            for(int j=i+1;j<nums.length;j++){
                if(nums[j]>nums[i]){
                    arr[i] = nums[j];
                    b = true;
                    break;
                }                
            }
            if(!b){
            for(int j=0;j<i;j++){
                if(nums[j]>nums[i]){
                    arr[i] = nums[j];
                    b = true;
                    break;
                }       
            }
            }
            if(b == false)
                arr[i] = -1;
        }
        return arr;
    }
}


Problem solution in C++.

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        if(nums.size() == 0) return {};
        vector<int> ans(nums.size(), -1);
        int maxElem = nums[0];
        for(int i = 0; i<nums.size(); i++){
            if(maxElem < nums[i]) maxElem = nums[i];
        }
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] != maxElem){
                int j = i + 1;
                while( j != i){
                    if(j == nums.size()) j = 0;
                    else{
                        if(nums[j] > nums[i]){
                            ans[i] = nums[j];
                            break;
                        }
                        else j++;
                    }
                }
            }
        }
        return ans;
    }
};


Post a Comment

0 Comments