Given a non-empty array of integers, return thekmost frequent elements.
For example,
Given[1,1,1,2,2,3]and k = 2, return[1,2].
Note:
You may assume?k?is always valid, 1 ≤k≤ number of unique elements.
our algorithm's time complexity must be better than O(nlogn), where?n?is the array's size.
思路: hashMap 一下, 然后建立一個list<Integer> 的數組用來存數字, 數組的索引就是數字重復出現的字數。這樣出現數字次數最多的就存在數組的后端。 從后讀數組的值取出返回。
還有一個O(nLogn )的方法, 重點在于set 沒法排序于是把set轉成list 再排序:
List<Map.Entry<Integer, Integer>> entry?= new LinkedList<>(map.entrySet());