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

    Problem:

    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.

    思路

    Solution (C++):

    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        if (nums1.empty() || nums2.empty())  return {};
        
        stack<int> stk;
        unordered_map<int, int> hash;
        
        for (auto x : nums2) {
            while (!stk.empty() && stk.top() < x) {
                hash[stk.top()] = x;
                stk.pop();
            }
            stk.push(x);
        }
        vector<int> res;
        for (auto x : nums1) {
            res.push_back(hash.count(x) ? hash[x] : -1);
        }
        return res;
    }
    

    性能

    Runtime: 12 ms  Memory Usage: 7.4 MB

    思路

    Solution (C++):

    
    

    性能

    Runtime: ms  Memory Usage: MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    敏捷开发宣言
    OpenGL SL 优化要点
    Cocoa Touch 开发框架
    MSIL详解
    Android之Services
    Android之ActivityII
    Android之Activity
    托管执行过程
    Android之Content ProviderII
    Android之Content Providers
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12699172.html
Copyright © 2011-2022 走看看