Java most easy solution with (n^2).


  • 0
    Q

    This solution is not efficient but very easy to understand.

    public class Solution {
        public int[] nextGreaterElement(int[] findNums, int[] nums) {
            int[] result=new int[findNums.length];
    // go through each element in findNums
            for(int i=0;i<findNums.length;i++)
            {
                for(int j=0;j<nums.length;j++)
                { // if we find one findNums element in second array, set result[i]=-1
                    if(findNums[i]==nums[j])
                    {
                        result[i]=-1;
                    }// if we already find the element in second array, and we can find a next greater number, set the value to the greater value;
                    if(result[i]==-1&&nums[j]>findNums[i])
                    {
                        result[i]=nums[j];
                    }
                }
            }
            return result;
        }
    }

Log in to reply
 

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