leetcode Next Greater Element I 下一个更大的元素

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.

Note:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.
在数组nums2中找到与nums1相等的元素,然后找到该元素之后第一个大于该元素的值。
1、最容易想到的方法,时间复杂度O(n^3).

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        vector<int> ans;
        for (int i = 0; i < findNums.size(); ++i) {
            int flag = 0;
            for (int j = 0; j < nums.size() - 1; ++j)
                if (nums[j] == findNums[i])
                    for (int k = j + 1; k if (nums[k] > findNums[i]) {
                            ans.push_back(nums[k]);
                            flag = 1;
                            break;
                        }
            if (!flag) ans.push_back(-1);
        }
        return ans;
    }
};

2、维持一个非递增数组,存储在栈中,当下一个元素比栈顶大时,依次出栈,直到栈顶大于等于该元素时,停止出栈,该元素入栈,此时所有出栈的元素的下一个更大元素为该元素,存储在hashmap中,时间复杂度为O(n)。

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        stack<int> s;
        unordered_map<int, int> m;
        for (int n : nums) {
            while (s.size() && s.top() < n) {
                m[s.top()] = n;
                s.pop();
            }
            s.push(n);
        }
        vector<int> ans;
        for (int n : findNums) ans.push_back(m.count(n) ? m[n] : -1);
        return ans;
    }
};

你可能感兴趣的:(leetcode)