【Leetcode】1762. Buildings With an Ocean View

题目地址:

https://leetcode.com/problems/buildings-with-an-ocean-view/

给定一个长 n n n的数组 A A A,求其所有满足其右边要么没有数,要么所有数都比它小的数的下标。要按升序排列。

思路是单调栈,可以从右往左遍历,入栈的时候判断该数的右边是否有比其大于等于的数,如果没有,则该数满足条件。代码如下:

class Solution {
 public:
  vector<int> findBuildings(vector<int>& h) {
    vector<int> res;
    stack<int> stk;
    for (int i = h.size() - 1; i >= 0; i--) {
      while (stk.size() && h[stk.top()] < h[i]) stk.pop();
      if (stk.empty()) res.push_back(i);
      stk.push(i);
    }

    reverse(res.begin(), res.end());
    return res;
  }
};

时空复杂度 O ( n ) O(n) O(n)

你可能感兴趣的:(LC,栈,队列,串及其他数据结构,leetcode,算法,c++)