zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    php函数
    字符滚动效果0515复习笔记+注释
    0514复习Windows操作及DOM的使用
    超链接文字随状态改变变色2016-0514
    js笔记之影音插入0514
    js类型转换,运算符,语句
    JS学习1简介
    json文件的json.parse(data)方法时候碰到的问题
    样式属性
    css样式表0513补
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8970453.html
Copyright © 2011-2022 走看看