The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.
Return an array _ans of length nums1.length such that ans[i] is the next greater element as described above._

Q:数组元素的下一个最大值。

Constraints:

  • 1 <= nums1.length <= nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 10^4
  • All integers in nums1 and nums2 are unique.
  • All the integers of nums1 also appear in nums2.

Example 1:

  1. Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
  2. Output: [-1,3,-1]
  3. Explanation: The next greater element for each value of nums1 is as follows:
  4. - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
  5. - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
  6. - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4]
Output: [3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.

解决思路1:暴力搜索,双循环遍历

解决思路2:单调栈+散列表

遍历nums2,每遇到一个新元素,判断栈顶元素与新元素

  • 如果栈顶元素大,则新元素不可能是栈内元素的下一个较大值,新元素入栈;
  • 如果新元素大,则栈顶元素的下一个最大值是新元素,记入map中, 弹出栈顶元素;继续判断,直至栈顶元素大于新元素,然后将新元素入栈 ;
  • 最后栈内剩余元素都是无下一个较大值的,也即其下一个较大值是-1。
  • 维护的栈从栈顶到栈底是单调不降的(按入栈的顺序是单调不增的),因此称为单调栈。

    代码:
    class Solution {
    public:
      vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
          map<int, int> num2ge;
          stack<int> ss;
          for(int& x:nums2){
              while(!ss.empty() && ss.top()<x){
                  num2ge[ss.top()] = x;
                  ss.pop();
              }
              ss.push(x);
          }
          while(!ss.empty()){
              num2ge[ss.top()] = -1;
              ss.pop();
          }
    
          vector<int> result(nums1.size(), 0);
          for(int i=0; i<nums1.size(); i++){
              result[i] = num2ge[nums1[i]];
          }
    
          return result;
      }
    };
    

    运行效率评价:

    Runtime: 8 ms, faster than 63.90% of C++ online submissions for Next Greater Element I.
    Memory Usage: 8.9 MB, less than 56.43% of C++ online submissions for Next Greater Element I.