Skip to content

Commit a886318

Browse files
committed
add prob #496; O(N) in time and O(N) in space;
1 parent d3192bd commit a886318

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

496_Next_Greater_Element_I.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
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.
3+
4+
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.
5+
6+
Example 1:
7+
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
8+
Output: [-1,3,-1]
9+
Explanation:
10+
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
11+
For number 1 in the first array, the next greater number for it in the second array is 3.
12+
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
13+
Example 2:
14+
Input: nums1 = [2,4], nums2 = [1,2,3,4].
15+
Output: [3,-1]
16+
Explanation:
17+
For number 2 in the first array, the next greater number for it in the second array is 3.
18+
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
19+
Note:
20+
All elements in nums1 and nums2 are unique.
21+
The length of both nums1 and nums2 would not exceed 1000.
22+
23+
来源:力扣(LeetCode)
24+
链接:https://leetcode-cn.com/problems/next-greater-element-i
25+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
26+
*/
27+
28+
/* O(N) in time and O(N) in space */
29+
#include <vector>
30+
#include <stack>
31+
#include <unordered_map>
32+
using namespace std;
33+
34+
class Solution {
35+
public:
36+
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
37+
unordered_map<int, int> val2idx;
38+
vector<int> res(nums1.size(), -1);
39+
stack<int> s;
40+
41+
for(int i=0; i<(int)nums1.size(); ++i){
42+
val2idx[nums1[i]] = i;
43+
}
44+
45+
for(int i=0; i<(int)nums2.size(); ++i){
46+
while( (!s.empty())&&(s.top()<nums2[i]) ){
47+
res[val2idx[s.top()]] = nums2[i];
48+
s.pop();
49+
}
50+
51+
if(val2idx.end()!=val2idx.find(nums2[i])){
52+
s.push(nums2[i]);
53+
}
54+
}
55+
56+
return res;
57+
}
58+
};

0 commit comments

Comments
 (0)