-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
28 lines (27 loc) · 867 Bytes
/
solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function nextGreaterElements (nums: number[]): number[] {
const stackNum:number[] = [];
const stackIndex:number[] = [];
const result:number[] = new Array(nums.length).fill(-1);
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
while (stackNum.length && stackNum[stackNum.length - 1] < num) {
const index = stackIndex.pop();
result[index] = num;
stackNum.pop();
}
stackNum.push(num);
stackIndex.push(i);
}
for (let i = 0; i < nums.length; i++) {
if (stackNum.length === 0) {
break;
}
const num = nums[i];
while (stackNum.length && stackNum[stackNum.length - 1] < num) {
const index = stackIndex.pop();
result[index] = num;
stackNum.pop();
}
}
return result;
}