Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 83cc298

Browse files
committed
Next Greater Element II
1 parent ba8815a commit 83cc298

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Source : https://leetcode.com/problems/diagonal-traverse/
2+
// Author : Han Zichi
3+
// Date : 2017年02月07日
4+
5+
/**
6+
* @param {number[]} nums
7+
* @return {number[]}
8+
*/
9+
var nextGreaterElements = function(nums) {
10+
let len = nums.length;
11+
nums = nums.concat(nums.slice(0, len - 1));
12+
13+
let ans = [];
14+
let stack = [];
15+
16+
// 单调队列?
17+
nums.forEach((item, index) => {
18+
if (index === 0) {
19+
stack.push({
20+
num: item,
21+
index: index
22+
});
23+
} else {
24+
while (true) {
25+
if (!stack.length) break;
26+
if (item > stack[stack.length - 1].num) {
27+
let lastItem = stack.pop();
28+
ans[lastItem.index] = item;
29+
} else {
30+
break;
31+
}
32+
}
33+
34+
stack.push({
35+
num: item,
36+
index: index
37+
});
38+
}
39+
});
40+
41+
ans = ans.slice(0, len);
42+
for (let i = 0; i < len; i++)
43+
if (ans[i] === undefined)
44+
ans[i] = -1;
45+
46+
return ans;
47+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /