leetcode Day44 剑指专项41-42

73 阅读1分钟

875. 爱吃香蕉的珂珂

var minEatingSpeed = function(piles, h) {
    let l=0,k=Math.max(...piles)
    let res=k
    while(l<k){
        let m=Math.floor((k-l)/2)+l
        let time=getTime(m,piles)
        if(time<=h){
            res=m
            k=m
        }else{
            l=m+1
        }
    }
    return res
};
const getTime=(speed,piles)=>{
    let time=0
    for(let i of piles){
        time+=Math.ceil((i/speed))
    }
    return time
}

剑指 Offer II 041. 滑动窗口的平均值

var MovingAverage = function(size) {
    this.nums=[]
    this.l=size
    this.sum=0

};

/** 
 * @param {number} val
 * @return {number}
 */
MovingAverage.prototype.next = function(val) {
    this.nums.push(val)
    this.sum+=val
    if(this.nums.length>this.l){
        this.sum-=this.nums.shift()
    }
    return this.sum/this.nums.length
};

剑指 Offer II 042. 最近请求次数

var RecentCounter = function() {
    this.opt=[]
};

/** 
 * @param {number} t
 * @return {number}
 */
RecentCounter.prototype.ping = function(t) {
    this.opt.push(t)
    this.count=0
    while(this.opt[0]<t-3000){
        this.opt.shift()
    }
    return this.opt.length
};