Zheaoli / do-something-right

MIT License
37 stars 3 forks source link

2022-05-06 #229

Open Zheaoli opened 2 years ago

Zheaoli commented 2 years ago

2022-05-06

dreamhunter2333 commented 2 years ago
package main

/*
 * @lc app=leetcode.cn id=933 lang=golang
 *
 * [933] 最近的请求次数
 */

// @lc code=start
type RecentCounter struct {
    count int
    data  []int
}

func Constructor() RecentCounter {
    return RecentCounter{0, make([]int, 0)}
}

func (this *RecentCounter) Ping(t int) int {
    for i := this.count; i < len(this.data); i++ {
        if t-this.data[i] <= 3000 {
            break
        }
        this.count += 1
    }
    this.data = append(this.data, t)
    return len(this.data) - this.count
}

/**
 * Your RecentCounter object will be instantiated and called as such:
 * obj := Constructor();
 * param_1 := obj.Ping(t);
 */
// func main() {
//  obj := Constructor()
//  fmt.Println(obj.Ping(1), obj.Ping(100), obj.Ping(3001), obj.Ping(3002))
// }
// @lc code=end

微信id: 而我撑伞 来自 vscode 插件

SaraadKun commented 2 years ago

933. 最近的请求次数

image

class RecentCounter {

    private int[] seq;

    private int oldest;

    private int lastest;

    private boolean flag;

    public RecentCounter() {
        seq = new int[3003];
        oldest = 0;
        lastest = 0;
    }

    public int ping(int t) {
        if (lastest == 3003) {
            lastest = 0;
            flag = !flag;
        }
        seq[lastest++] = t;
        int target = t - 3000;
        while (seq[oldest] < target && flag ^ (oldest < lastest)){
            oldest++;
            if (oldest == 3003) {
                oldest = 0;
                flag = !flag ;
            }
        }
        return flag ? lastest + 3003 - oldest : lastest - oldest;
    }
}

WeChat:Saraad