496. Next Greater Element I

1. 原始题目

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.

2. 题目理解

题目大意是nums1 = [4,1,2] ,nums2=[1,3,4,2]。首先4对应nums2的right的位置为[4,2],没有比4大的数,返回-1。1对应nums2的right的位置[1,2,4,2],第一个比1大的数为3,返回3。2对应muns2的right的位置为[],返回-1。

3. 解法

1)常规解法(python3)

思路:首先对nums1中每个元素先找到在nums2中的下标,然后再看后面的元素有无大于nums1该元素的结果。运行效率很低,多个循环:

 1 class Solution:
 2     def nextGreaterElement(self, nums1, nums2):
 3         stack = []
 4         for i in nums1:
 5 
 6             for j in range(len(nums2)):
 7                 if j==(len(nums2)-1):
 8                     stack.append(-1)
 9                     break
10                 if (i==nums2[j]):
11                     for k in range(j+1, len(nums2)):
12                         if nums2[k]>i:
13                             stack.append(nums2[k])
14                             break
15                         if (k==len(nums2)-1) and nums2[k]<=i:
16                             stack.append(-1)
17                     break
18         return stack

2)优秀解法(C++)

思路:因为nums1中每个元素都在nums2里,所以只针对nums2即可。对于nums2中每个元素,若栈空则直接进,否则对比当前元素是否比栈里的大,若满足,则建立对应字典,并且依次出栈,新元素进栈。最后以nums1中元素为键来索引,返回结果。

class Solution {
private:
    stack<int> Stack;
    map<int, int> Map;
    vector<int> results;
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        for (int i : nums2)
        {
            while ((!Stack.empty()) && (Stack.top() < i)){
                Map.insert({ Stack.top(), i });
                Stack.pop();
            }                
            Stack.push(i);
        }

        for (int i : nums1)
            if (Map.count(i) == 1)
                results.push_back(Map.at(i));
            else
                results.push_back(-1);
        return results;
    }
};
原文地址:https://www.cnblogs.com/king-lps/p/10635448.html