本文共 1884 字,大约阅读时间需要 6 分钟。
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given[1,1,1,2,2,3]
and k = 2, return [1,2]
. Note:
O(n log n)
, where n is the array’s size.//Runtime: 43 mspublic class Solution { private void buildHeap(ArrayList> entries, int root, int len) { int left = 2 * root + 1; if (left < len) { int largest = left; int right = left + 1; if (right < len && entries.get(right).getValue() > entries.get(largest).getValue()) { largest = right; } if (entries.get(root).getValue() < entries.get(largest).getValue()) { Map.Entry entry = entries.get(root); entries.set(root, entries.get(largest)); entries.set(largest, entry); buildHeap(entries, largest, len); } } } private void heapSort(ArrayList > entries) { int len = entries.size(); for (int i = len / 2; i >= 0; i--) { buildHeap(entries, i, len); } for (int i = len - 1; i > 0; i--) { Map.Entry entry = entries.get(0); entries.set(0, entries.get(i)); entries.set(i, entry); buildHeap(entries, 0, --len); } } public List topKFrequent(int[] nums, int k) { Map map = new HashMap (); for (int num : nums) { if (map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } } ArrayList > entries = new ArrayList >(map.entrySet()); heapSort(entries); List list = new ArrayList (k); for (int i = entries.size() - 1; i >= entries.size() - k; i--) { list.add(entries.get(i).getKey()); } return list; }}
转载地址:http://epenx.baihongyu.com/