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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    socket server的N种并发模型
    进程、线程以及Goroutine的区别
    分布式从ACID、CAP、BASE的理论推进
    epoll的理论与IO阻塞机制
    golang面试题知识点总结
    golang中如何进行项目模块及依赖管理
    面对golang中defer,要注意什么?
    Kaggle 学习之旅
    推荐在线学习读书网站
    k8s 的 dashboard 的实践
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12699172.html
Copyright © 2011-2022 走看看