LeetCode——Next Greater Element I

LeetCode——Next Greater Element I

Question

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.c++

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:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.數組

解題思路

想的就是過濾一遍第二個數組,把每一個數右邊比它大的第一個數存起來,而後遍歷第一個數組,爲每一個元素找到第一個大的元素。this

具體實現

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

        vector<int> res;
        for (int i : findNums) {
            res.push_back(dict[i]);
        }
        return res;
    }
};

相關解答中,用到了棧來遍歷第二個數組,這樣的時間複雜度會下降到O(n),而以上這個算法的時間複雜度爲O(n^2)。code

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;
    }
};
相關文章
相關標籤/搜索