Java HashMap 9ms, easy to understand


  • 0
    public class Solution {
        public int[] nextGreaterElement(int[] findNums, int[] nums) {
            ArrayList<Integer> res = new ArrayList<Integer>();
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                map.put(nums[i], i);
            }
            for (int j = 0; j < findNums.length; j++) {
                for (int k = map.get(findNums[j]); k < nums.length; k++) {
                    if (nums[k] > findNums[j]) {
                        res.add(nums[k]);
                        break;
                    }
                    if (k == nums.length - 1) {
                        res.add(-1);
                    }
                }
            }
            
            int[] re = new int[res.size()];
            for (int k = 0; k < res.size(); k++) {
                re[k] = res.get(k);
            }
     
            return re;
        }
    }
    

Log in to reply
 

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