LeetCode 347. Top K Frequent Elements(最频繁的K个元素)

原题网址:https://leetcode.com/problems/top-k-frequent-elements/

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.

使用两个映射:num --> frequency,和frequency --> nums

public class Solution {
    public List topKFrequent(int[] nums, int k) {
        Map frequency = new HashMap<>();
        int max = 0;
        for(int num: nums) {
            Integer f = frequency.get(num);
            if (f == null) f = 1; else f ++;
            frequency.put(num, f);
            max = Math.max(max, f);
        }
        List[] inverse = new List[max+1];
        for(int num: frequency.keySet()) {
            int f = frequency.get(num);
            if (inverse[f] == null) inverse[f] = new ArrayList<>();
            inverse[f].add(num);
        }
        List result = new ArrayList<>();
        for(int i=max; i>0; i--) {
            if (result.size() == k) break;
            if (inverse[i] == null) continue;
            for(int j=0; j

方法二:对哈希映射计数表进行排序。

public class Solution {
    public List topKFrequent(int[] nums, int k) {
        Map frequency = new HashMap<>();
        for(int num: nums) {
            Integer f = frequency.get(num);
            if (f == null) f = 1; else f ++;
            frequency.put(num, f);
        }
        int[] uniques = new int[frequency.size()];
        int[] f = new int[uniques.length];
        int i = 0;
        for(Map.Entry entry: frequency.entrySet()) {
            uniques[i] = entry.getKey();
            f[i] = entry.getValue();
            i++;
        }
        Integer[] n = new Integer[uniques.length];
        for(int j=0; j() {
            @Override
            public int compare(Integer i1, Integer i2) {
                return Integer.compare(f[i2], f[i1]);
            }
        });
        List results = new ArrayList<>();
        for(int j=0; j

不合适使用摩尔投票算法,因为题目是找最频繁,而不是找频率超过1/k的数字。

你可能感兴趣的:(哈希,映射,哈希映射,双向映射,频率)