|
| 1 | +// Source : https://leetcode.com/problems/number-of-recent-calls/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2020-07-26 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * Write a class RecentCounter to count recent requests. |
| 8 | + * |
| 9 | + * It has only one method: ping(int t), where t represents some time in milliseconds. |
| 10 | + * |
| 11 | + * Return the number of pings that have been made from 3000 milliseconds ago until now. |
| 12 | + * |
| 13 | + * Any ping with time in [t - 3000, t] will count, including the current ping. |
| 14 | + * |
| 15 | + * It is guaranteed that every call to ping uses a strictly larger value of t than before. |
| 16 | + * |
| 17 | + * Example 1: |
| 18 | + * |
| 19 | + * Input: inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]] |
| 20 | + * Output: [null,1,2,3,3] |
| 21 | + * |
| 22 | + * Note: |
| 23 | + * |
| 24 | + * Each test case will have at most 10000 calls to ping. |
| 25 | + * Each test case will call ping with strictly increasing values of t. |
| 26 | + * Each call to ping will have 1 <= t <= 10^9. |
| 27 | + * |
| 28 | + ******************************************************************************************************/ |
| 29 | + |
| 30 | +class RecentCounter { |
| 31 | +public: |
| 32 | + RecentCounter() { |
| 33 | + |
| 34 | + } |
| 35 | + |
| 36 | + int ping(int t) { |
| 37 | + req.push_back(t); |
| 38 | + return req.size() - binary_search(t-3000); |
| 39 | + } |
| 40 | +private: |
| 41 | + vector<int> req; |
| 42 | + int binary_search(int x) { |
| 43 | + int low=0, high=req.size()-1; |
| 44 | + while(low < high) { |
| 45 | + int mid = low + (high -low) / 2; |
| 46 | + if ( req[mid] == x ) return mid; |
| 47 | + if ( req[mid] < x ) low = mid + 1; |
| 48 | + else high = mid - 1; |
| 49 | + } |
| 50 | + cout << "x=" << x << "\tlow=" << low << endl; |
| 51 | + return x > req[low] ? low+1 : low ; |
| 52 | + } |
| 53 | +}; |
| 54 | + |
| 55 | +/** |
| 56 | + * Your RecentCounter object will be instantiated and called as such: |
| 57 | + * RecentCounter* obj = new RecentCounter(); |
| 58 | + * int param_1 = obj->ping(t); |
| 59 | + */ |
0 commit comments