• 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.

  • 相关阅读:
    03《高效程序员的45个习惯》阅读笔记2
    02《高效程序员的45个习惯》阅读笔记1
    关于“foreach循环”中遇到的几个问题总结
    pageContext.request.contextPath} JSP取得绝对路径
    读书笔记1
    java中字节数组byte[]和字符(字符串)之间的转换
    本学期阅读计划
    问题账户需求分析
    准备食物
    【bzoj4551】【NOIP2016模拟7.11】树
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6637851.html
Copyright © 2020-2023  润新知