Next Greater Element

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.

Example1

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.

Example2

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.

My Solution

题意比较容易理解,解体思路也比较清晰,但没有使用栈这一数据结构,导致冗余运算。

class Solution {
public:
    vector nextGreaterElement(vector& findNums, vector& nums) {
        map numsMap;
        for(int i = 0; i < nums.size(); i++){
            int key = nums[i];
            int value;
            bool isGreater = false;
            for (int j = i + 1; j < nums.size(); j++){
                if (key < nums[j]){
                   value = nums[j];
                   isGreater = true;
                   break;
                }
            }
            if (!isGreater){
                value = -1;
            }
            numsMap.insert(make_pair(key, value));
        }
        
        vector result;
        for (int i = 0; i < findNums.size(); i++){
            result.push_back(numsMap[findNums[i]]);
        }
        return result;
    }
};

时间负责度: O(N) = O(n2) //n的平方

Efficien Solution

 假设有这样的序列[5, 4, 3, 2, 1, 6];对于元素5,4,3,2,1,其符合条件的元素都为位于序列末尾的6。如果采用My Solution,将产生许多冗余比较。
 在这个算法我们借助栈,对于序列进行迭代。如果栈为空,元素入栈;如果栈不空且栈顶元素大于此元素,元素入栈;否则,弹出栈顶元素存储结果直至栈顶元素大于此元素。
 对于序列[9, 8, 7, 3, 2, 1, 6];序列迭代到6时,栈结果为[9, 8, 7, 3, 2, 1];后续栈弹出 [1, 2, 3]。代码如下(Java)

 public int[] nextGreaterElement(int[] findNums, int[] nums) {
        Map map = new HashMap<>(); // map from x to next greater element of x
        Stack stack = new Stack<>();
        for (int num : nums) {
            while (!stack.isEmpty() && stack.peek() < num)
                map.put(stack.pop(), num);
            stack.push(num);
        }   
        for (int i = 0; i < findNums.length; i++)
            findNums[i] = map.getOrDefault(findNums[i], -1);
        return findNums;
    }

时间负责度: O(N) = O(n + m) = O(n) (n > m)

你可能感兴趣的:(Next Greater Element)