By Map


  • 0
    X
    private final Map<Integer, Integer> map = new LinkedHashMap<>();
    
    /** Record a hit.
        @param timestamp - The current timestamp (in seconds granularity). */
    public void hit(int timestamp) {
        map.put(timestamp, map.getOrDefault(timestamp, 0) + 1);
        Iterator<Map.Entry<Integer, Integer>> iter = map.entrySet().iterator();
    
        while (iter.hasNext()) {
            final Map.Entry<Integer, Integer> next = iter.next();
    
            if (timestamp - next.getKey() > 300) {
                iter.remove();
            } else {
                break;
            }
        }
    }
    
    /** Return the number of hits in the past 5 minutes.
        @param timestamp - The current timestamp (in seconds granularity). */
    public int getHits(int timestamp) {
        return map.entrySet().stream().filter(e -> timestamp - e.getKey() <= 300).mapToInt(e -> e.getValue()).sum();
    }
    
    

Log in to reply
 

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