查看題目詳情可點擊此處。
題目
Write a class RecentCounter to count recent requests.
It has only one method: ping(int t), where t represents some time in milliseconds.
Return the number of pings that have been made from 3000 milliseconds ago until now.
Any ping with time in [t - 3000, t] will count, including the current ping.
It is guaranteed that every call to ping uses a strictly larger value of t than before.
Example 1:
Input: inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]
Output: [null,1,2,3,3]
Note:
- Each test case will have at most 10000 calls to ping.
- Each test case will call ping with strictly increasing values of t.
- Each call to ping will have 1 <= t <= 10^9.
解題思路
當將 t 作為參數調用 ping 方法時,需要去除在 t - 3000 至 t 范圍外的值,由于每次調用 ping 的數值是從小至大,所以 t 是現在通過 ping 存儲過的最大值,不滿足條件的數據肯定只能小于 t - 3000,那從被存儲的最小值開始找直到數據滿足條件為止,返回存儲的數據量即可。
這個操作使先調用 ping 方法存儲起來的值被先刪除掉,滿足先進先出的特點,使用隊列比較合適,我也嘗試使用數組的方式,利用二分查找查找最后一位小于 t - 3000 數據元素的方式解決,不過通過 leetcode 測試用例的耗時和使用隊例的差距并不大,應該是每次滿足刪除條件的數據量不多,所以逐個遍歷和使用二分查找需要比較數據個數差距不大。
代碼實現
private Queue<Integer> queue = new LinkedList<>();
// by queue
public int ping(int t) {
queue.add(t);
while(queue.peek() < t - 3000) {
queue.poll();
}
return queue.size();
}
private List<Integer> array = new ArrayList<>();
private int startIndex = 0;
// by array
public int pingByArray(int t) {
array.add(t);
int targetIndex = searchLastLess(array, t - 3000);
if(targetIndex >= 0) {
startIndex = targetIndex + 1;
}
return array.size() - startIndex;
}
private int searchLastLess(List<Integer> array, int target) {
if(array == null || array.size() < 1) {
return -1;
}
int low = 0, high = array.size() - 1;
while(low <= high) {
int mid = low + ((high - low) >> 1);
if(array.get(mid) >= target) {
high = mid - 1;
} else {
if(mid == array.size() - 1 || array.get(mid + 1) >= target) {
return mid;
} else {
low = mid + 1;
}
}
}
return -1;
}
代碼詳情可點擊查看 我的 GitHub 倉庫