My solution using HashMap


  • 0
    F

    According to :
    https://discuss.leetcode.com/topic/48758/super-easy-design-o-1-hit-o-s-gethits-no-fancy-data-structure-is-needed

    I write a hashmap version, the hit() performance should be better than O(300), any comments are welcome:

    public class HitCounter {
    	HashMap<Integer, Integer> map;
    	int[] hits;
    
    	public HitCounter() {
    		map = new HashMap<Integer, Integer>();
    		hits = new int[300];
    	}
    
    	public void hit(int timestamp) {
    		int index = timestamp % 300;
    		if (!map.containsKey(index) || map.get(index)!= timestamp) {
    			hits[index]=1;
    			map.put(index, timestamp);
    		} else {
    			hits[index]++;
    		}		
    	}
    
    	public int getHits(int timestamp) {
    		int res = 0;
    		Set<Integer> keys = map.keySet();
    		for (Integer key : keys) {
    			if (timestamp-map.get(key)<300) {
    				res+=hits[key];
    			}				
    		}
    		return res;
    	}
    }
    

Log in to reply
 

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