1 public class HitCounter { 2 private int[] count; 3 private int[] indexes; 4 5 /** Initialize your data structure here. */ 6 public HitCounter() { 7 count = new int[300]; 8 indexes = new int[300]; 9 for (int i = 0; i < 300; i++) { 10 indexes[i] = i; 11 } 12 } 13 14 /** Record a hit. 15 @param timestamp - The current timestamp (in seconds granularity). */ 16 public void hit(int timestamp) { 17 int index = timestamp % 300; 18 if (timestamp != indexes[index]) { 19 indexes[index] = timestamp; 20 count[index] = 0; 21 } 22 count[index]++; 23 } 24 25 /** Return the number of hits in the past 5 minutes. 26 @param timestamp - The current timestamp (in seconds granularity). */ 27 public int getHits(int timestamp) { 28 int result = 0; 29 for (int i = 0; i < 300; i++) { 30 result += timestamp - indexes[i] < 300 ? count[i] : 0; 31 } 32 return result; 33 } 34 } 35 36 /** 37 * Your HitCounter object will be instantiated and called as such: 38 * HitCounter obj = new HitCounter(); 39 * obj.hit(timestamp); 40 * int param_2 = obj.getHits(timestamp); 41 */
1. 300 is not included
原文:http://www.cnblogs.com/shuashuashua/p/5619664.html