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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    修改注册表改变程序默认安装路径
    任务管理器在右下角的图标不显示
    WORD中插入的公式与文字对不齐——公式比文字高——文字比公式低
    tablespace
    使用Working Set让eclipse环境看着更清爽
    Grub4DOS 0.4.4 下载
    Windows和Linux操作系统下Eclipse开发C/C++程序的代码提示
    不同的编译器:GCC G++ C C++的区别
    oracle基础
    JS相关
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12699172.html
Copyright © 2011-2022 走看看