LeetCode OJ 347. Top K Frequent Elements hashmap+排序求解
Posted bruce128
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 347. Top K Frequent Elements hashmap+排序求解相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/problems/top-k-frequent-elements/、
347. Top K Frequent Elements
My SubmissionsGiven 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:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm‘s time complexity must be better than O(n log n), where n is the array‘s size.
Subscribe to see which companies asked this question
求词频最高的k个词。用hashmap统计词频。然后按词频排序,排序可以用归并排序或者堆排序。Collections.sort()底层用的是归并排序。PriorityQueue底层用的是堆排序。两种算法堆排序的性能略占优。
给出两种算法的AC代码:
package march; import java.util.*; /** * Created by Administrator on 2016/6/16. */ public class TopKFrequentElements { public static void main(String[] args) { int[] a = {1, 1, 1, 2, 2, 3}; System.out.println(topKFrequent(a, 2)); System.out.println(topKFrequent2(a, 2)); int[] b = {-1, -1}; System.out.println(topKFrequent(b, 1)); System.out.println(topKFrequent2(b, 1)); } // 归并排序 public static List<Integer> topKFrequent(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length); for (int n : nums) { Integer val = map.get(n); map.put(n, val == null ? 1 : val + 1); } List<Map.Entry<Integer, Integer>> l = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet().size()); l.addAll(map.entrySet()); Collections.sort(l, new Comparator<Map.Entry<Integer, Integer>>() { @Override public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return -(o1.getValue() - o2.getValue()); } }); List<Integer> result = new ArrayList<Integer>(k); for (int i = 0; i < k; i++) { result.add(l.get(i).getKey()); } return result; } // 堆排序 public static List<Integer> topKFrequent2(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length); for (int n : nums) { Integer val = map.get(n); map.put(n, val == null ? 1 : val + 1); } PriorityQueue<Map.Entry<Integer, Integer>> q = new PriorityQueue<Map.Entry<Integer, Integer>>(map.entrySet().size(), new Comparator<Map.Entry<Integer, Integer>>() { @Override public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return -(o1.getValue() - o2.getValue()); } }); q.addAll(map.entrySet()); List<Integer> result = new ArrayList<Integer>(k); for (int i = 0; i < k; i++) { result.add(q.poll().getKey()); } return result; } }
以上是关于LeetCode OJ 347. Top K Frequent Elements hashmap+排序求解的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 347. Top K Frequent Elements
#Leetcode# 347. Top K Frequent Elements
Leetcode 347: Top K Frequent Elements
leetcode347 - Top K Frequent Elements - medium