Java simple O(nm) solution


  • 0
    M

    Go through the first array and find the element on the second array, after that simply find if there is a next greater element.

    public class Solution {
        public int[] nextGreaterElement(int[] findNums, int[] nums) {
            List<Integer> result = new ArrayList<>();
            for (int i = 0; i < findNums.length; i++) {
    
                int target = findNums[i];
                int next = -1;
    
                int j = 0;
                //place the pointer to the target element.
                while (nums[j] != target) {
                    j++;
                }
                
                //point to the next element.
                j++;
    
                while (j < nums.length) {
                    if (nums[j] > target && nums[j] > next) {
                        next = nums[j];
                        break;
                    }
                    j++;
                }
    
                result.add(next);
            }
            return result.stream().mapToInt(i -> i).toArray();
        }
    }
    

Log in to reply
 

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