[LeetCode] Top K Frequent Elements

Problem

Given a non-empty array of integers, return the k most frequent elements.

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.

Solution

public class Solution {
    public List topKFrequent(int[] nums, int k) {
        int n = nums.length;
        Map map = new HashMap<>();
        for (int num: nums) {
            if (map.containsKey(num)) map.put(num, map.get(num)+1);
            else map.put(num, 1);
        }
        List[] freq = new ArrayList[n+1];
        for (int num : map.keySet()) {
            int i = map.get(num);
            if (freq[i] == null) {
                freq[i] = new ArrayList<>();
            }
            freq[i].add(num);
        }
        List res = new ArrayList<>();
        for (int index = freq.length - 1; index >= 0 && res.size() < k; index--) {
            if (freq[index] != null) {
                res.addAll(freq[index]);
            }
        }
        return res;
    }
}

Update 2018-9

PriorityQueue

class Solution {
    public List topKFrequent(int[] nums, int k) {
        List res = new ArrayList<>();
        if (nums == null || nums.length < k) return res;
        Map map = new HashMap<>();
        PriorityQueue> queue = new PriorityQueue<>((a, b)->b.getValue()-a.getValue());
        for (int num: nums) {
            map.put(num, map.getOrDefault(num, 0)+1);
        }
        for (Map.Entry entry: map.entrySet()) {
            queue.offer(entry);
        }
        int count = 0;
        while (count < k) {
            Map.Entry entry = queue.poll();
            res.add(entry.getKey());
            count++;
        }
        return res;
    }
}

Bucket sort

class Solution {
    public List topKFrequent(int[] nums, int k) {
        List res = new ArrayList<>();
        if (nums == null || nums.length < k) return res;
        Map map = new HashMap<>();
        for (int num: nums) {
            map.put(num, map.getOrDefault(num, 0)+1);
        }
        List[] buckets = new ArrayList[nums.length+1];
        for (Map.Entry entry: map.entrySet()) {
            int value = entry.getValue();
            if (buckets[value] == null) buckets[value] = new ArrayList<>();
            buckets[value].add(entry.getKey());
        }
        for (int i = buckets.length-1; i >= 0 && res.size() < k; i--) {
            if (buckets[i] != null) res.addAll(buckets[i]);
        }
        return res;
    }
}

你可能感兴趣的:(java,hashmap,bucket)