Skip to content

Commit 5f5f7f3

Browse files
committed
5 April 2017:496.Next Greater Element I
1 parent 2a43153 commit 5f5f7f3

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public:
3+
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
4+
stack<int> s;
5+
unordered_map<int, int> m;
6+
//遍历nums中的元素
7+
for (auto e : nums){
8+
//堆栈s为空并且堆栈s的栈顶的元素小于e元素,将元素写入map中,key值为栈顶元素,value值为比栈顶元素大的元素
9+
while(!s.empty() && s.top() < e){
10+
m[s.top()] = e;
11+
s.pop();
12+
}
13+
s.push(e);
14+
}
15+
vector<int> ans;
16+
//查找findNums中元素,如果m中存在n,返回m[n]的valuse值,如果不存在返回-1
17+
for (auto n : findNums){
18+
ans.push_back(m.count(n) ? m[n] : -1);
19+
}
20+
return ans;
21+
}
22+
};
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public:
3+
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
4+
stack<int> s;
5+
unordered_map<int, int> m;
6+
//遍历nums中的元素
7+
for (auto e : nums){
8+
//堆栈s为空并且堆栈s的栈顶的元素小于e元素,将元素写入map中,key值为栈顶元素,value值为比栈顶元素大的元素
9+
while(!s.empty() && s.top() < e){
10+
m[s.top()] = e;
11+
s.pop();
12+
}
13+
s.push(e);
14+
}
15+
vector<int> ans;
16+
//查找findNums中元素,如果m中存在n,返回m[n]的valuse值,如果不存在返回-1
17+
for (auto n : findNums){
18+
ans.push_back(m.count(n) ? m[n] : -1);
19+
}
20+
return ans;
21+
}
22+
};

0 commit comments

Comments
 (0)