力扣题-11.3
力扣题1:901. 股票价格跨度
解题思想:通过栈记录(idx, price)的组合即可
class StockSpanner(object):
def __init__(self):
self.stack = [(-1, float('inf'))]
self.idx = -1
def next(self, price):
"""
:type price: int
:rtype: int
"""
self.idx += 1
while price >= self.stack[-1][1]:
self.stack.pop()
self.stack.append((self.idx, price))
return self.idx - self.stack[-2][0]
class StockSpanner {
public:
std::stack<std::pair<int, int>> stack;
int idx = -1;
StockSpanner() {
stack.push({-1, INT_MAX});
}
int next(int price) {
idx +=1;
while(price>=stack.top().second){
stack.pop();
}
stack.push({idx, price});
pair<int, int> temp = stack.top();
stack.pop();
pair<int, int> temp2 = stack.top();
stack.push(temp);
return idx - temp2.first;
}
};
/**
* Your StockSpanner object will be instantiated and called as such:
* StockSpanner* obj = new StockSpanner();
* int param_1 = obj->next(price);
*/
力扣题2:42. 接雨水
解题思想:通过栈保存(i, height)的组合,保持栈是递减的
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
stack = []
result= 0
for i in range(len(height)):
while stack and stack[-1][1] < height[i]:
temp = stack.pop()
if not stack:
break
current = stack[-1]
width = i - current[0]-1
high = min(current[1], height[i]) - temp[1]
result += width * high
stack.append((i,height[i]))
return result
class Solution {
public:
int trap(vector<int>& height) {
std::stack<std::pair<int, int>> stack;
int result =0;
for(int i=0;i<height.size();i++){
while(!stack.empty() && stack.top().second<height[i]){
pair<int, int> temp = stack.top();
stack.pop();
if(stack.empty()){
break;
}
pair<int, int> current = stack.top();
int width = i-current.first -1;
int high =0;
if(current.second<height[i]){
high = current.second - temp.second;
}
else{
high = height[i] - temp.second;
}
result+=width*high;
}
stack.push({i,height[i]});
}
return result;
}
};