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.
    

    Note:

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

    链接:https://leetcode.com/problems/next-greater-element-i/#/description

    3/29/2017

    不会做,看别人的做法

    解释也非常好:https://discuss.leetcode.com/topic/77916/java-10-lines-linear-time-complexity-o-n-with-explanation

    #单调序列和stack#

     1 public class Solution {
     2     public int[] nextGreaterElement(int[] findNums, int[] nums) {
     3         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
     4         Stack<Integer> s = new Stack<Integer>();
     5         int[] ret = new int[findNums.length];
     6 
     7         for (int i = 0; i < nums.length; i++) {
     8             while (!s.isEmpty() && s.peek() < nums[i]) {
     9                 hm.put(s.pop(), nums[i]);
    10             }
    11             s.push(nums[i]);
    12         }
    13         for (int i = 0; i < findNums.length; i++) {
    14             ret[i] = hm.getOrDefault(findNums[i], -1);
    15         }
    16         return ret;
    17     }
    18 }

    Python时间复杂度O(MN)的算法:

    1 def nextGreaterElement(self, findNums, nums):
    2     return [next((y for y in nums[nums.index(x):] if y > x), -1) for x in findNums]

    更多讨论:https://discuss.leetcode.com/category/645/next-greater-element-i

  • 相关阅读:
    对拍
    311随笔
    精彩才刚刚开始
    做不下去了,就开心一下吧。
    情书
    论Sue这个人呐(=@__@=)
    P1113 杂务
    P1546 最短网络 Agri-Net
    P2009 跑步
    P2814 家谱
  • 原文地址:https://www.cnblogs.com/panini/p/6644593.html
Copyright © 2011-2022 走看看