496. Next Greater Element I 另一个数组中对应的更大元素

Posted 排序和map

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了496. Next Greater Element I 另一个数组中对应的更大元素相关的知识,希望对你有一定的参考价值。

[抄题]:

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1\'s elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

 

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
    For number 2 in the first array, the next greater number for it in the second array is 3.
    For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

 [暴力解法]:

时间分析:

空间分析:新建res数组存nums1的结果

 [优化后]:

时间分析:

空间分析:反正是查询index,就地存储即可

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

感觉用stack的题都挺难的,基本靠背。总结下。

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. stack应该搭配while循环,别粗心写成if

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

stack当备胎池,有用的结果有选择性地放在别的地方

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

stack当备胎池,只有最上端开口,只处理当下元素

有用的结果有选择性地放在hashmap里

[关键模板化代码]:

[其他解法]:

[Follow Up]:

Next Greater Element II 还是用stack

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        //ini: stack, map
        Stack<Integer> stack = new Stack<>();
        Map<Integer, Integer> map = new HashMap<>();
        
        //store in stack and map
        for (int num : nums2) {
            //bigger,put into map
            while (!stack.isEmpty() && num > stack.peek()) {
                map.put(stack.pop(), num);
            }
            stack.push(num);
        }
        
        //get res from map
        for (int i = 0; i < nums1.length; i++) {
            nums1[i] = map.getOrDefault(nums1[i], -1);
        }
        
        //return
        return nums1;
    }
}
View Code

 

以上是关于496. Next Greater Element I 另一个数组中对应的更大元素的主要内容,如果未能解决你的问题,请参考以下文章

leetcode496 - Next Greater Element I - easy && leetcode503 - Next Greater Element II - medi

496. Next Greater Element I

496. Next Greater Element I

496. Next Greater Element I

496. Next Greater Element I

496. Next Greater Element I