9ms,beats 86.45% of java submissions.


  • 0
    C
    public int[] nextGreaterElement2(int[] findNums, int[] nums) {
            int[] result = new int[findNums.length];
    
            if (findNums.length > 0) {
                HashMap<Integer, Integer> maps = new HashMap<>();
                maps.put(nums[nums.length - 1], -1);
                for (int i = nums.length - 2; i >= 0; i--) {
                    if (nums[i] < nums[i + 1]) {
                        maps.put(nums[i], nums[i + 1]);
                    }
                    else {
                        int j = i + 1;
                        while (j < nums.length - 1) {
                            int temp = maps.get(nums[j]);
                            if (nums[i] < temp) {
                                maps.put(nums[i], temp);
                                break;
                            }
                            j++;
                        }
                        if (j == nums.length - 1) {
                            maps.put(nums[i], -1);
                        }
                    }
                }
                for (int i = 0; i < findNums.length; i++) {
                    result[i] = maps.get(findNums[i]);
                }
            }
            return result;
        }

Log in to reply
 

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