Brute Force O(MN) O(1) space Java AC


  • 0
    J

    This question desecription is confusing.
    The goal of the problem is to find the next greater element in nums2.

    Suppose we're interested in finding the next greater element for element c in nums1.

    1. First locate c in nums2, c must exist since nums1 is a subset of nums2
    2. Scan every element to the right of c in nums2, find the first one that is > c, -1 if we can't find it
        public int[] nextGreaterElement(int[] findNums, int[] nums) {
            int[] res = new int[findNums.length];
            
            for(int i = 0; i < findNums.length; i++){
                boolean found = false;
                for(int j = 0; j < nums.length; j++){
                    if(nums[j] == findNums[i]){
                        for(int k = j; k < nums.length; k++){
                            if(nums[k] > nums[j]){
                                found = true;
                                res[i] = nums[k];
                                break;
                            }
                        }
                    }
                    if(!found){
                        res[i] = -1;
                    }
                }
            }
            
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.