HashMap,like pigeonSortO(kn),not fastest but easy to implement


  • 0
    D
    	public List<Integer> topKFrequent( int[] nums, int k ) {
    	List<Integer> list = new ArrayList<Integer>();
    	Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
    	for( int n : nums ) {
    		int val = ( Integer )getOrDefault( hashMap, n, 0 ) + 1;
    		hashMap.put( n, val );
    	}
    	for( int i = 0; i < k; i++ ) {
    		int max = 0;
    		int maxKey = 0;
    		for( Map.Entry<Integer, Integer> entry : hashMap.entrySet() ) {
    			if( entry.getValue() > max ) {
    				maxKey = entry.getKey();
    				max = entry.getValue();
    			}
    		}
    		list.add( maxKey );
    		hashMap.remove( maxKey );
    	}
    	return list;
    }
    
    public Object getOrDefault( Map map, Object key, Object defaultValue ) {
    	Object o = map.get( key );
    	if( null == o )
    		return defaultValue;
    	return o;
    }

Log in to reply
 

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