leetcode 347. Top K Frequent Elements | 347. 前 K 个高频元素(大根堆)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 347. Top K Frequent Elements | 347. 前 K 个高频元素(大根堆)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
https://leetcode.com/problems/top-k-frequent-elements/
題解
參考:leetcode 215. Kth Largest Element in an Array | 215. 數(shù)組中的第K個(gè)最大元素(Java)
class Solution {public static class HeapNode {int num;int count;public HeapNode(int num, Integer count) {this.num = num;this.count = count;}}public int[] topKFrequent(int[] nums, int k) {HashMap<Integer, Integer> map = new HashMap<>();for (int n : nums) {if (!map.containsKey(n)) map.put(n, 1);else map.put(n, map.get(n) + 1);}// 建大根堆int heapSize = map.size();HeapNode[] heap = new HeapNode[heapSize];int j = 0;for (int key : map.keySet())heap[j++] = new HeapNode(key, map.get(key));for (int i = heapSize - 1; i >= 0; i--) // 自下向上建堆 可證復(fù)雜度為O(n)heapify(heap, i, heapSize);// Top kint[] result = new int[k];int pos = 0;for (int i = 0; i < k; i++) {result[pos++] = heap[0].num;swap(heap, 0, --heapSize);heapify(heap, 0, heapSize);}return result;}public void heapify(HeapNode[] heap, int i, int heapSize) {int left = i * 2 + 1;while (left < heapSize) {int largest = left + 1 < heapSize && heap[left + 1].count > heap[left].count ? left + 1 : left; // 左右孩子較大者的下標(biāo)largest = heap[largest].count > heap[i].count ? largest : i; // 兩個(gè)孩子與父節(jié)點(diǎn)較大者的下標(biāo)if (largest == i) break; // 不需要交換的情況swap(heap, largest, i);i = largest; // 更新i使其下沉left = 2 * i + 1;}}private void swap(HeapNode[] heap, int i, int j) {HeapNode tmp = heap[i];heap[i] = heap[j];heap[j] = tmp;} }總結(jié)
以上是生活随笔為你收集整理的leetcode 347. Top K Frequent Elements | 347. 前 K 个高频元素(大根堆)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: leetcode 355. Design
- 下一篇: leetcode 365. Water