当前位置:网站首页>Force deduction solution summary 933- number of recent requests

Force deduction solution summary 933- number of recent requests

2022-06-12 02:08:00 Lost summer

Directory links :

Force buckle programming problem - The solution sums up _ Share + Record -CSDN Blog

GitHub Synchronous question brushing items :

https://github.com/September26/java-algorithms

Original link : Power button


describe :

Write a  RecentCounter  Class to calculate the most recent request in a specific time range .

Please realize RecentCounter class :

RecentCounter() Initialize counter , The number of requests is 0 .
int ping(int t) In time t Add a new request , among t Represents a time in milliseconds , And go back to the past 3000 The number of all requests in milliseconds ( Including new requests ). To be precise , Back in the [t-3000, t] The number of requests that occurred in .
Guarantee Every time the ping All calls to the t value .

Example 1:

Input :
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
Output :
[null, 1, 2, 3, 3]

explain :
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1);     // requests = [1], The scope is [-2999,1], return 1
recentCounter.ping(100);   // requests = [1, 100], The scope is [-2900,100], return 2
recentCounter.ping(3001);  // requests = [1, 100, 3001], The scope is [1,3001], return 3
recentCounter.ping(3002);  // requests = [1, 100, 3001, 3002], The scope is [2,3002], return 3
 

Tips :

1 <= t <= 109
Make sure you do it every time ping The... Used by the call t It's worth it Strictly increasing
Call at most ping Method 104 Time

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/number-of-recent-calls
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Their thinking :

*  Their thinking :
*  It is most appropriate to store the results of the queue , Because the title provides t Is increasing , So every time you add numbers, you start traversing from the front of the queue , If it does not meet the scope, remove , Otherwise, exit the loop .
*  Finally, just return the number of queues .

Code :

public class Solution933 {

    class RecentCounter {

        Queue<Integer> queue = new ArrayDeque<>();

        public RecentCounter() {

        }

        public int ping(int t) {
            int i = t - 3000;
            Iterator<Integer> iterator = queue.iterator();
            while (iterator.hasNext()) {
                Integer next = iterator.next();
                if (next < i) {
                    iterator.remove();
                    continue;
                }
                break;
            }
            queue.offer(t);
            return queue.size();
        }
    }

}

原网站

版权声明
本文为[Lost summer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120202544163.html