Share my easy to understand solution


  • 0
    E

    Share my solution with less memory than the top thread.
    Basically I keep a start pointer so I can remove the already past timestamps based on coming timestamp and a sum for fast retrieval.

    public class HitCounter {
        int[] map;
        int start, sum;
        public HitCounter() {
            map = new int[300];
            start = 1;
            sum = 0;
        }
        
        public void hit(int timestamp) {
            moveForward(timestamp);
            map[(timestamp - 1) % 300]++;
            sum++;
        }
        
        public int getHits(int timestamp) {
            moveForward(timestamp);
            return sum;
        }
        
        private void moveForward(int timestamp) {
            if (timestamp - start >= 600) {
                start = timestamp;
                sum = 0;
                for (int i = 0; i < 300; i++) map[i] = 0;
            }
            for (int i = start; i <= timestamp - 300; i++) {
                sum -= map[(i - 1) % 300];
                map[(i - 1) % 300] = 0;
                start++;
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.