- 数组元素值竟然是首尾相连的
- 一般思路是将原数组扩大到其2倍,即把元素再复制出一模一样的另一套
- 不扩大数组的思路是,遍历元素时,要按照元素个数的2倍来遍历
- 这样遍历的话,就会出现元素下标超出范围的情况
- 解决这个问题就可以使用取模的方式,即与元素长度取模,就可以解决下标超范围的问题
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int len = nums.size();
std::vector<int> result(len, -1);
if (len == 0) {
return result;
}
std::stack<int> stack_indices;
stack_indices.push(0);
for (int i = 1; i < len * 2; ++i) {
int index = i % len;
if (nums[index] <= nums[stack_indices.top()]) {
stack_indices.push(index);
} else {
do {
result[stack_indices.top()] = nums[index];
stack_indices.pop();
} while (!stack_indices.empty() && nums[index] > nums[stack_indices.top()]);
stack_indices.push(index);
}
}
return result;
}
};
标签:index,nums,元素,随想录,len,stack,indices,第四十八,503
From: https://blog.csdn.net/taoyong001/article/details/145579666