problem:https://leetcode.com/problems/next-greater-element-ii/
一道比较简单的单调队列题目。不过由于题目要求是循环的,需要两个pass,第二个pass处理循环生效的next greater,同时需要把下标已经超出范围的队首数据及时pop出来。
class Solution { public: vector<int> nextGreaterElements(vector<int>& nums) { deque<int> q; vector<int> res(nums.size(), -1); for (int i = 0; i < nums.size(); i++) { while (!q.empty() && nums[i] > nums[q.back()]) { res[q.back()] = nums[i]; q.pop_back(); } q.push_back(i); } for (int i = 0; i < nums.size(); i++) { while (!q.empty() && nums[i] > nums[q.back()]) { res[q.back()] = nums[i]; q.pop_back(); } while (!q.empty() && q.front() <= i)q.pop_front(); if (q.empty())break; } return res; } };
原文地址:https://www.cnblogs.com/fish1996/p/11268300.html
时间: 2024-10-14 08:05:12