问题:
难度:easy
说明:
调用时候会实例化一个StockSpanner,然后不断调用StockSpanner.next(int input),从输入参数输入股票价值,然后返回该天的跨度,跨度就是从今天之前的连续的天数,且比今天价值还少的天数数量。
输入案例:
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:
// 第一天100就一天是1
S.next(100) is called and returns 1,
S.next(80) is called and returns 1,
S.next(60) is called and returns 1,
// 70之前还有60所以两天是2
S.next(70) is called and returns 2,
S.next(60) is called and returns 1,
// 75之前有三天比他少是4
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.
输入范围:
输入的股票个数<=10000,整个测试流程会有150000个
我的代码:
是一个动态规划处理。
class StockSpanner {
int[] priceStack = new int[10000];
int[] spanStack = new int[10000];
int top = -1;
public StockSpanner() {
}
public int next(int price) {
int span = 1;
while(top >= 0 && priceStack[top] <= price) span += spanStack[top --];
top ++;
priceStack[top] = price;
spanStack[top] = span;
return span;
}
}
这个代码我发现居然效率特别低,然后换了一下。
class StockSpanner {
int[] priceStack;
int[] spanStack;
int top = -1;
// 将数组实例化放到构造方法
public StockSpanner() {
priceStack = new int[10000];
spanStack = new int[10000];
}
public int next(int price) {
int span = 1;
while(top >= 0 && priceStack[top] <= price) span += spanStack[top --];
top ++;
priceStack[top] = price;
spanStack[top] = span;
return span;
}
}
然后这个效率奇高。看来java的构造方法初始化值效率特别快比构造器还快,具体原因不明,截图为证。