Created
July 30, 2016 00:05
-
-
Save jianminchen/0626a0cb673526d4b7b58698004b87b8 to your computer and use it in GitHub Desktop.
LC 347 - K most Frequent bucket sort - Java - study code - source: http://www.guoting.org/leetcode/leetcode-347-top-k-frequent-elements/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public List<Integer> topKFrequent(int[] nums, int k){ | |
List<Integer>[] bucket=new List[nums.length+1]; | |
Map<Integer,Integer> frequencyMap=new HashMap<>(); | |
for(int n:nums){ | |
frequencyMap.put(n,frequencyMap.getOrDefault(n,0)+1); | |
} | |
for(int key:frequencyMap.keySet()){ | |
int frequency=frequencyMap.get(key); | |
if(bucket[frequency]==null){ | |
bucket[frequency]=new ArrayList<>(); | |
} | |
bucket[frequency].add(key); | |
} | |
List<Integer> res=new ArrayList<>(); | |
for(int pos=bucket.length-1;pos>=0;pos--){ | |
if(bucket[pos]!=null){ | |
for(Integer i:bucket[pos]){ | |
if(res.size()<k){ | |
res.add(i); | |
}else{ | |
return res; | |
} | |
} | |
} | |
} | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment