Skip to content

Commit

Permalink
June24: nextGreaterElement II, use circular [M]
Browse files Browse the repository at this point in the history
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
aucker committed Jun 24, 2024
1 parent 87efb7c commit d02daac
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions daily/June24.cpp
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;
}
};

0 comments on commit d02daac

Please sign in to comment.