Java with HashMap


  • 1
    T

    public class Solution {

    public List<Integer> topKFrequent(int[] nums, int k) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        
        HashMap<Integer, Integer> num = new HashMap<Integer, Integer>(); //used to count the number of each unique element
        for (int i =0; i < nums.length; i++){
            if (!num.containsKey(nums[i])){
                num.put(nums[i], 1);
            } else{
                num.put(nums[i], num.get(nums[i])+1);
            }
        }
        
        
        for (int j = 1; j<=k ;j++){ 
            int max = 0; // the max count number of one element
            int val = 0; // the value of the max counted number
            
            for (Map.Entry<Integer, Integer> entry:num.entrySet()){ // search for the max count number
                if (max < entry.getValue()){
                    max = entry.getValue();
                    val = entry.getKey();
                } 
            }
            result.add(val);
            num.remove(val); 
            
        }
       return result; 
    }
    

    }


  • 0
    L

    O(n)????????????????


  • 0
    B

    i think it's O(k*n)


  • 0
    O

    It is actually O(n^2) as we can have k equal to n.


Log in to reply
 

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