Java, TreeMap solution


  • 0
    D
    public class HitCounter {
    
        private TreeMap<Integer, Integer> map;
        
        /** Initialize your data structure here. */
        public HitCounter() 
        {
            map = new TreeMap<>();
        }
        
        /** Record a hit.
            @param timestamp - The current timestamp (in seconds granularity). */
        public void hit(int timestamp) 
        {
            map.put(timestamp, map.getOrDefault(timestamp, 0) + 1);  
        }
        
        /** Return the number of hits in the past 5 minutes.
            @param timestamp - The current timestamp (in seconds granularity). */
        public int getHits(int timestamp) 
        {
            int count = 0;
            int floor = timestamp - 299;
            
            for (Map.Entry<Integer, Integer> e : map.subMap(floor, true, timestamp, true).entrySet())
            {
                count += e.getValue();
            }
            return count;
        }
    }
    

Log in to reply
 

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