496. Next Greater Element I(python+cpp)

题目:

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

解释:
给定数组nums1nums2,其中nums1nums2的子数组,为nums1中的每个元素在nums2中找到位于其右的第一个比其大的数字,如果不存在,为这个数字返回-1

使用字典和栈,建立每个数字和其右边第一个较大数之间的映射,没有的话就是-1。 我们遍历原数组nums2中的所有数字,如果此时栈不为空,且栈顶元素小于当前数字,说明当前数字就是栈顶元素的右边第一个较大数,那么建立二者的映射,并且去除当前栈顶元素,最后将当前遍历到的数字压入栈(用while循环判断)。当所有数字都建立了映射,那么最后我们可以直接通过哈希表快速的找到子集合中数字的右边较大值。

python代码:

class Solution(object):
    def nextGreaterElement(self, findNums, nums):
        """
        :type findNums: List[int]
        :type nums: List[int]
        :rtype: List[int]
        """
        stack=[]
        _dict={}
        for num in nums:
            while stack!=[] and stack[-1]<num:
                _dict[stack.pop()]=num
            stack.append(num)
        result=[]
        for fn in findNums:
            result.append(_dict.get(fn,-1))
        return result

为什么要用while而不用if? 因为一个num可能是stack中好几个元素的右边第一个最大值
c++代码:

#include 
#include 
#include 
class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        stack<int> _stack;
        unordered_map<int ,int> _map;
        for(auto num:nums)
        {
            while (!_stack.empty() && _stack.top()<num)
            {
                _map[_stack.top()]=num;
                _stack.pop();
            }
            _stack.push(num);
        }
        vector<int> result;
        map<int ,int>::iterator iter;
        for (auto f:findNums)
        {   iter=_map.find(f);
            if (iter!=_map.end())
                result.push_back(iter->second);
            else
                result.push_back(-1);
        }
        return result;
    }
};

总结:

你可能感兴趣的:(LeetCode)