• 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
  • 相关阅读:
    构造函数产生的点及原因
    关于未捕获异常的处理(WPF)
    消息协定
    为outlook增加“邮件召回”功能
    MHA故障切换和在线手工切换原理
    Delphi 类型转换函数(有几个函数没见过,FloatToStrF,FloatToText等等)
    Delphi 常用属性说明(超长)
    Delphi程序自删除的几种方法
    CreateFile,ReadFile等API详解(或者说MSDN的翻译)
    去除文件属性(使用SetFileAttributes API函数)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8970453.html
Copyright © 2020-2023  润新知