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.

  • 相关阅读:
    memcached +mysql+php 例子
    PHP利用memcache缓存技术提高响应速度
    实现QQ第三方登录教程(php)
    php如何解决多线程同时读写一个文件的问题
    php数组函数常见的那些
    PHP 5种方式获取文件后缀名
    函数与方程
    函数图像习题
    高中数学中需要重点关注的函数和图像
    特殊分段函数的图像画法
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6637851.html
Copyright © 2011-2022 走看看