-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
June24: nextGreaterElement II, use circular [M]
use stack to handle, but len is 2 times of original length traverse once, so time and space will be both O(N)
- Loading branch information
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
#include <bits/stdc++.h> | ||
using namespace std; | ||
|
||
class Solution { | ||
public: | ||
/** | ||
* @brief LC: 503: Next Greater Element II | ||
* Use stack | ||
* Time: O(N), Space: O(N) | ||
* | ||
* @param nums | ||
* @return vector<int> | ||
*/ | ||
vector<int> nextGreaterElements(vector<int>& nums) { | ||
int len = nums.size(); | ||
vector<int> ans(len, -1); | ||
|
||
stack<int> stk; | ||
for (int i = 2 * len - 1; i >= 0; i--) { | ||
int x = nums[i % len]; | ||
while (!stk.empty() && x >= stk.top()) { | ||
stk.pop(); | ||
} | ||
if (i < len && !stk.empty()) { | ||
ans[i] = stk.top(); | ||
} | ||
stk.push(x); | ||
} | ||
return ans; | ||
} | ||
|
||
/** | ||
* @brief nextGreaterElementsII, but from left to right | ||
* Still Stack | ||
* Time: O(N), Space: O(N) | ||
* | ||
* @param nums | ||
* @return vector<int> | ||
*/ | ||
vector<int> nextGreaterElementsII(vector<int>& nums) { | ||
int len = nums.size(); | ||
vector<int> ans(len, -1); | ||
stack<int> stk; | ||
for (int i = 0; i < 2 * len; i++) { | ||
int x = nums[i % len]; | ||
while (!stk.empty() && x > nums[stk.top()]) { | ||
ans[stk.top()] = x; | ||
stk.pop(); | ||
} | ||
if (i < len) { | ||
stk.push(i); | ||
} | ||
} | ||
return ans; | ||
} | ||
}; |