zoukankan      html  css  js  c++  java
  • LeetCode 496. Next Greater Element I

    原题链接在这里:https://leetcode.com/problems/next-greater-element-i/#/description

    题目:

    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.

    Note:

    1. All elements in nums1 and nums2 are unique.
    2. The length of both nums1 and nums2 would not exceed 1000.

    题解:

    对于nums2中的每一个元素,找到next greater element并对应放到HashMap<Integer, Integer> hm 中.

    如何一遍找到呢,通过Stack<Integer> stk, 从右向左扫面,新的元素num会把stk顶部比num小的全部pop出去, 剩下的顶部就是next greater element, 存到hm中.

    stk便成了从顶向下增大的栈. 最后利用hm把findNums的每个元素对应的next greater element找出来.

    Time Complexity: O(n), n = nums2.length.

    Space: O(n).

    AC Java:

     1 class Solution {
     2     public int[] nextGreaterElement(int[] nums1, int[] nums2) {
     3         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
     4         Stack<Integer> stk = new Stack<Integer>();
     5         
     6         for(int i = nums2.length-1; i>=0; i--){
     7             while(!stk.isEmpty() && nums2[i]>=nums2[stk.peek()]){
     8                 stk.pop(); 
     9             }
    10             
    11             int nextGreater = stk.isEmpty() ? -1 : nums2[stk.peek()];
    12             hm.put(nums2[i], nextGreater);
    13                 
    14             stk.push(i);
    15         }
    16         
    17         int [] res = new int[nums1.length];
    18         for(int i = 0; i<nums1.length; i++){
    19             res[i] = hm.get(nums1[i]);
    20         }
    21         
    22         return res;
    23     }
    24 }

     跟上Next Greater Element IIDaily Temperatures.

  • 相关阅读:
    orm添加表记录
    创建多表模型
    包的使用
    日志写法
    os模块,是通过和操作系统交互进行操作
    sys python解释器做交互
    软件开发规范
    模块 time模块 datatime模块 random模块
    装饰器
    装饰器进阶
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6637851.html
Copyright © 2011-2022 走看看