You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
varStockSpanner=function(){// 存储股票跨度this.spanner=[]// 存储股票价格this.stockPrice=[]};/** * @param {number} price * @return {number} */StockSpanner.prototype.next=function(price){// 对于第一天进行特殊判断if(!this.spanner.length){this.spanner.push(1)this.stockPrice.push(price)// 直接返回1return1}letcnt=0letidx=this.stockPrice.length-1while(price>=this.stockPrice[idx]&&idx>=0){cnt+=this.spanner[idx]idx-=this.spanner[idx]}// 加上本身cnt++// 进行更新操作,将当前股票价格和跨度入栈this.spanner.push(cnt)this.stockPrice.push(price)returncnt};/** * Your StockSpanner object will be instantiated and called as such: * var obj = new StockSpanner() * var param_1 = obj.next(price) */
varStockSpanner=function(){this.spannerArr=[];this.prices=[];};/** * @param {number} price * @return {number} */StockSpanner.prototype.next=function(price){if(this.spannerArr.length===0){this.prices.push(price);this.spannerArr.push(1);return1;}letendIndex=this.prices.length-1;letcnt=1;while(this.prices[endIndex]<=price&&endIndex>=0){cnt+=this.spannerArr[endIndex];endIndex-=this.spannerArr[endIndex];}this.prices.push(price);this.spannerArr.push(cnt);returncnt;};/** * Your StockSpanner object will be instantiated and called as such: * var obj = new StockSpanner() * var param_1 = obj.next(price) */
varStockSpanner=function(){this.map=[]this.spanner=[]};/** * @param {number} price * @return {number} */StockSpanner.prototype.next=function(price){letres=1if(!this.spanner.length){this.spanner.push(1)this.map.push(price)return1}leti=this.map.length-1while(this.map[i]<=price&&i>=0){res+=this.spanner[i]i=i-this.spanner[i]}this.map.push(price)this.spanner.push(res)returnres};/** * Your StockSpanner object will be instantiated and called as such: * var obj = new StockSpanner() * var param_1 = obj.next(price) */
题目描述
编写一个
StockSpanner
类,它收集某些股票的每日报价,并返回该股票当日价格的跨度。今天股票价格的跨度被定义为股票价格小于或等于今天价格的最大连续日数(从今天开始往回数,包括今天)。
例如,如果未来7天股票的价格是
[100, 80, 60, 70, 60, 75, 85]
,那么股票跨度将是[1, 1, 1, 2, 1, 4, 6]
。示例:
提示:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/online-stock-span
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
正如题意,我们要求当前元素之前,比自己小(可以相等)的元素个数,并且元素个数包括本身,那么我们最后的结果应该还要加1.
于是按题意,我们采用跨度法,举个例子,对于例子6,1,2,3,4,9,从后往前逆推一下,当我们新插入9的时候,如果发现前一位的4比9小,那么是否说明比9小的数量就等于比4小的数量加1?然而这是错的,因为首位的6比9小,却比4大,因此截止数字的4时候,比4小的数量中并不包含6与9的对比。
因此,我们还要跳到 6 的位置再去计算小于等于自己的元素。
最后
文章产出不易,还望各位小伙伴们支持一波!
往期精选:
小狮子前端の笔记仓库
访问超逸の博客,方便小伙伴阅读玩耍~
学如逆水行舟,不进则退
The text was updated successfully, but these errors were encountered: