原题如下:
Write a class StockSpanner
which collects daily price quotes for some stock, and returns the span of that stock’s price for the current day.
The span of the stock’s price today is defined as the maximum number of consecutive days (starting from today and going backwards) for which the price of the stock was less than or equal to today’s price.
For example, if the price of a stock over the next 7 days were [100, 80, 60, 70, 60, 75, 85]
, then the stock spans would be [1, 1, 1, 2, 1, 4, 6]
.
中文解释:要计算某天的价格的span,就是从当天开始往回算,连续几天的价格小于等于当天的价格,当天的span就是几。
Example 1:
Input: [“StockSpanner”,“next”,“next”,“next”,“next”,“next”,“next”,“next”], [[],[100],[80],[60],[70],[60],[75],[85]]
Output: [null,1,1,1,2,1,4,6]
Explanation:
First, S = StockSpanner() is initialized. Then:
S.next(100) is called and returns 1,
S.next(80) is called and returns 1,
S.next(60) is called and returns 1,
S.next(70) is called and returns 2,
S.next(60) is called and returns 1,
S.next(75) is called and returns 4,
S.next(85) is called and returns 6.
Note that (for example) S.next(75) returned 4, because the last 4 prices
(including today’s price of 75) were less than or equal to today’s price.
Note:(这些可忽略)
- Calls to
StockSpanner.next(int price)
will have1 <= price <= 10^5
. - There will be at most
10000
calls toStockSpanner.next
per test case. - There will be at most
150000
calls toStockSpanner.next
across all test cases. - The total time limit for this problem has been reduced by 75% for C++, and 50% for all other languages.
思路
每个新的price对应一个span,每次加入一个price时,跟前面的price比较,若前面的比它小,则其span要加上前面的span,且该较小price的项应该删除,因为其span已经被加到后面price较大的项中去了,如果不删掉,下次会重复加span,导致错误,此外,这些项已经不需要用到,删掉可以节省空间。
对于每一项,可以定义一个结构体,包含一个price和span;然后再用一个容纳该结构体的vector容器,当做一个栈使用(也可以直接用stack);每次加入新项时,与前面的项的price相比,其span加上较小price的项的span,再pop掉相等或较小price的项,直到price大于当天的price,停止pop并把新项加入。
讲得比较绕口,举个例子:
比如依次添加的price为:[100, 80, 60, 70, 60, 75, 85]
则栈中的结构体依次为:(每个元素表示{price, span})
[{100, 1}]
[{100, 1}, {80, 1}]
[{100, 1}, {80, 1}, {60, 1}]
[{100, 1}, {80, 1}, {70, 2}] 注:插入70时发现60比较小,于是删掉60,且span=1+1=2
[{100, 1}, {80, 1}, {70, 2}, {60, 1}]
[{100, 1}, {80, 1}, {75, 4}] 注:插入75时发现60和70都比较小,于是删掉它们,且span=1+1+2=4
[{100, 1}, {85, 6}] 注:插入85时发现75和80都比较小,于是删掉它们,且span=1+4+1=6
c++代码
class StockSpanner {
public:
StockSpanner() {
}
int next(int price) {
node n;
n.last_price = price;
n.span = 1;
while(!spans.empty()){
// 看一下原来栈中的最后一项
node back = spans.back();
// 比较其price
if(back.last_price <= price){
n.span += back.span;
spans.pop_back();
}
else break;
}
spans.push_back(n);
return n.span;
}
private:
// 定义一个表示一天价格项的结构体
struct node{
int last_price;
int span;
};
vector<node> spans;
};