Leet Code知识点总结 - 496

LeetCode 496. Next Greater Element I

考点 难度
Array Easy
题目

The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.

You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.

For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.

Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

思路

除了iterate through两个array(O(N^2))之外的另一种解法(O(N)):
需要一个map和一个stack。stack储存decreasing subsequence。对于stack外的一个新数字x,如果x大于stack里面的第一个数字则pop整个stack,而pop出的所有数字的next greater element都是x。此时需要map,键存放数字,值存放next greater element。最后从map中找到对应位置即可。如果要找的数字没有存在map里面则返回默认值-1。
在写码的时候有一些技巧可以用到:

  1. stack.peek( ) 返回栈顶的元素,但不弹出该栈顶元素,如果stack是空则返回null
  2. map.getOrDefault(key, default value)在map里面查找key,返回对应的值,如果找不到则返回default value

另外复习stack和map的基本操作:

  1. stack.isEmpty( )判断stack是否是空
  2. stack.pop( )返回栈顶的元素,并且将该栈顶元素出栈
  3. map.put(key, value)储存新映射关系到map
答案
public int[] nextGreaterElement(int[] findNums, int[] nums) {
        Map<Integer, Integer> map = new HashMap<>(); // map from x to next greater element of x
        Stack<Integer> stack = new Stack<>();
        for (int num : nums) {
            while (!stack.isEmpty() && stack.peek() < num)
                map.put(stack.pop(), num);
            stack.push(num);
        }   
        for (int i = 0; i < findNums.length; i++)
            findNums[i] = map.getOrDefault(findNums[i], -1);
        return findNums;
    }

**解法来自:yuxiangmusic的答案

Guess you like

Origin blog.csdn.net/m0_59773145/article/details/119970412
Recommended