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

原文链接: https://www.cnblogs.com/dysjtu1995/p/12699172.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    496. Next Greater Element I

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/342106

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午1:25
下一篇 2023年3月2日 上午1:25

相关推荐