LeetCode OJ 347. Top K Frequent Elements hashmap+排序求解

    题目链接:https://leetcode.com/problems/top-k-frequent-elements/、

347. Top K Frequent Elements

  My Submissions
Question Editorial Solution
Total Accepted: 15510  Total Submissions: 36453  Difficulty: Medium

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: 

  • 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

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss Pick One

    

    求词频最高的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+排序求解)