Java easy solution only use array


  • 0
    W
    public class HitCounter {
    int[] hitcon = new int[601];
    int last = 600;
    /** Initialize your data structure here. */
    public HitCounter() {
       // int[] hitcon = new int[601];
        
    }
    
    /** Record a hit.
        @param timestamp - The current timestamp (in seconds granularity). */
    public void hit(int timestamp) {
        if (timestamp >= last) {
            for (int j = 301; j <= 600; j++) {
                hitcon[j - 300] = hitcon[j];
                hitcon[j] = 0;
            }
            last += 300;
        }
        if (timestamp <= 300) {
            hitcon[timestamp]++;
        } else {
            int t = timestamp % 300;
            hitcon[t + 300]++;
        }
    }
    
    /** Return the number of hits in the past 5 minutes.
        @param timestamp - The current timestamp (in seconds granularity). */
    public int getHits(int timestamp) {
        int time = 0;
        if (timestamp >= last) {
            for (int j = 301; j <= 600; j++) {
                hitcon[j - 300] = hitcon[j];
                hitcon[j] = 0;
            }
            last += 300;
        }
        if (timestamp <= 300) {
            for (int i = 1; i <= 300; i++) {
                time += hitcon[i];
            }
        } else {
            int t = timestamp % 300;
            for (int i = t + 1; i <= 300 + t; i++) {
                time += hitcon[i];
            }
        }
        return time;
    }
    

    }


Log in to reply
 

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