Object oriented solution


  • 0
    C

    This solution may not be the most memory efficient solution, but it solves the problem with high readability. Since this is a design question, more effort should be also made to the code cleanness. Because usually design question is expected to be answered by people with professional experience. Code cleanness is definitely a significant part of professionalism.

    public class HitCounter {
        private int totalHit;
        private Deque<Hit> hitRecords;
    
        public HitCounter() {
            hitRecords = new ArrayDeque<>(300);
            totalHit = 0;
        }
        
        public void hit(int timestamp) {
            if (!hitRecords.isEmpty() && timestamp == hitRecords.peekLast().ts) {
                hitRecords.peekLast().ct += 1;
            } else {
                hitRecords.add(new Hit(timestamp));
            }
            totalHit++;
        }
        
        public int getHits(int timestamp) {
            while (!hitRecords.isEmpty() && timestamp - hitRecords.peek().ts >= 300) {
                totalHit -= hitRecords.remove().ct;
            }
            return totalHit;
        }
        
        private class Hit {
            int ts;
            int ct;
            Hit(int ts) {
                this.ts = ts;
                ct = 1;
            }
        }
    }

Log in to reply
 

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