Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit a2cd98b

Browse files
committed
Add solution #503
1 parent 8a6204d commit a2cd98b

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

0503-next-greater-element-ii.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 503. Next Greater Element II
3+
* https://leetcode.com/problems/next-greater-element-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given a circular integer array nums (i.e., the next element of
7+
* nums[nums.length - 1] is nums[0]), return the next greater number
8+
* for every element in nums.
9+
*
10+
* The next greater number of a number x is the first greater number
11+
* to its traversing-order next in the array, which means you could
12+
* search circularly to find its next greater number. If it doesn't
13+
* exist, return -1 for this number.
14+
*/
15+
16+
/**
17+
* @param {number[]} nums
18+
* @return {number[]}
19+
*/
20+
var nextGreaterElements = function(nums) {
21+
const total = nums.length;
22+
const result = new Array(total).fill(-1);
23+
const stack = [];
24+
25+
for (let i = 0; i < 2 * total; i++) {
26+
while (stack.length && nums[i % total] > nums[stack[stack.length - 1]]) {
27+
result[stack.pop()] = nums[i % total];
28+
}
29+
stack.push(i % total);
30+
}
31+
32+
return result;
33+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@
165165
500|[Keyboard Row](./0500-keyboard-row.js)|Easy|
166166
501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy|
167167
502|[IPO](./0502-ipo.js)|Hard|
168+
503|[Next Greater Element II](./0503-next-greater-element-ii.js)|Medium|
168169
506|[Relative Ranks](./0506-relative-ranks.js)|Easy|
169170
509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy|
170171
520|[Detect Capital](./0520-detect-capital.js)|Easy|

0 commit comments

Comments
 (0)