Java 114ms runtime, but concise code.


  • 0
    S
    public class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            Map <Integer, Integer> bro = new HashMap <Integer, Integer>  (); 
            Integer tempo = 0; 
            for (int i = 0 ; i < nums.length; i++ ) {
                if (bro.containsKey (nums[i])) {
                    tempo = bro.get(nums[i])+ 1;
                    bro.remove(nums[i]);
                    bro.put(nums[i], tempo); 
                } else 
                    bro.put(nums[i], 1 ); 
                    
                
            }
            
            List<Integer> keys = new ArrayList <Integer> ( bro.keySet() ) ; 
            List<Integer> returnValues = new ArrayList <Integer> (); 
            Integer max = 0 , tmp = 0, key = 0; 
            int Done = 0 , keyRemove = 0; 
            //*
            while (Done != k) {
                max = 0; 
                for (int i =0 ; i < keys.size(); i ++  ) {
                    
                    if (bro.containsKey(keys.get(i)))
                    tmp = bro.get(keys.get(i) ) ;
                    if (max < tmp ) {
                        max = tmp; 
                        key = keys.get(i); 
                        keyRemove = i; 
                    }
                    
                }
                
                keys.remove(keyRemove);
                bro.remove(key);
                returnValues.add(Done, key); 
                Done ++; 
            } 
            //*/
            return returnValues; 
        }
    }
    
    

Log in to reply
 

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