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.
nums1时nums2的子数组。
找出nums1中对应元素在nums2中位置之后距离最近且大于此数的元素。
例如 nums[4, 1, 2], nums2[1,3,4,2]
对于4,在nums2中4之后的数只有2,但是4>2,所以返回-1
对于1,在nums2中1之后有3,4,2,最接近的且>1的为3
….
….
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
res = []
for i in range(0, len(findNums)):
t = nums.index(findNums[i])
flag = 0
for j in range(t+1, len(nums)):
if nums[j] > findNums[i]:
res.append(nums[j])
flag = 1
break
if flag==0:
res.append(-1)
return res
朴素解法比较容易想到但是比较耗时,既然这道题目是在分类stack中,百度了一下使用栈的解法。
思路:根据所给的nums2[]数组构造Next Greater Element 的映射。利用栈可进可退的灵活性。
用例子比较容易理解:
例如nums = [5, 4, 3, 2, 1, 7]
1. 初始化栈为空,5进栈。 栈中元素为:5
2. 4<5(栈顶元素) ,进栈。栈中元素为:5 4
3. 3<4, 进栈. 栈中元素为:5 4 3
4. 2<3, 进栈, 栈中元素为:5 4 3 2
5. 1<2, 进栈, 栈中元素为:5 4 3 2 1
6. 7>1(栈顶元素), 构建{1:7}, 1出栈,栈中元素为:5 4 3 2
7. 7>2(栈顶元素),构建{2:7}, 2出栈,栈中元素为:5 4 3
…..
直到栈为空,
构建映射为{1:7},{2:7},{3:7},{4:7},{5:7},{7:-1}
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
m = {}
stack = []
for i in range(0, len(nums)):+
m[nums[i]] = -1
while len(stack)!=0 and stack[-1]1]] = nums[i]
stack.pop()
stack.append(nums[i])
res = []
for i in range(0, len(findNums)):
res.append(m[findNums[i]])
return res
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
map<int, int>m;
stack<int>s;
for(int i=0; i1;
while(!s.empty()&&nums[i]>s.top()){
m[s.top()] = nums[i];
s.pop();
}
s.push(nums[i]);
}
vector<int>res;
for(int i=0; ireturn res;
}
};