Java Solution with HashMap and Stack / T : O(N), S : O(N)


  • 0
    J
    public int[] nextGreaterElement(int[] findNums, int[] nums) {
            HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
            Stack<Integer> st = new Stack<Integer>();
            int[] result = new int[findNums.length];
            
            for(int num : nums){
                while(!st.isEmpty() && st.peek() < num){
                    map.put(st.pop(), num);
                }
                st.push(num);
            }
            
            for(int i = 0; i < findNums.length; i++){
                result[i] = map.getOrDefault(findNums[i], -1);
            }
            
            return result;
        }
    

Log in to reply
 

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