BiruLyu
6/5/2017 - 6:03 PM

347. Top K Frequent Elements(Bucket).java

public class Solution {
    private class Node {
        int value;
        int count;
        public Node(int value, int count) {
            this.value = value;
            this.count = count;
        }
    }
    public List<Integer> topKFrequent(int[] nums, int k) {
        List<Integer> res = new ArrayList<Integer>();
        if(nums == null || nums.length == 0) return res;
        Queue<Node> queue = new PriorityQueue<Node>(new Comparator<Node>() {
            public int compare (Node n1, Node n2) {
                return n2.count - n1.count;
            }
        });
        Arrays.sort(nums);
        int count = 1;
        int len = nums.length;
        for(int i = 1; i < len; i++) {
            if(nums[i] == nums[i - 1]) {
                count++;
                continue;
            }
            queue.offer(new Node(nums[i - 1], count));
            count = 1;
        }
        queue.offer(new Node(nums[len - 1], count));
        
        
        for(int i = 0; i < k; i++) {
            res.add(queue.poll().value);
        }
        return res;
        
    }
}
public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        if (nums == null) return null;
        else if (nums.length < 1) return new ArrayList<Integer>();
        
        List<Integer> res = new ArrayList<Integer>();
        Arrays.sort(nums);
        List<Integer>[] countBucket = new List[nums.length+1];
        if (nums.length == 1) {
            countBucket[1] = new ArrayList<Integer>();
            countBucket[1].add(nums[0]);
        } else {
            int i = 0, count = 1;
            for (int j = 1; j < nums.length; j++) {
                if (nums[j] == nums[i]) count++;
                else { 
                    if (countBucket[count] == null) 
                        countBucket[count] = new ArrayList<Integer>();
                    countBucket[count].add(nums[i]);
                    i = j;
                    count = 1;
                }
            }
            if (countBucket[count] == null) 
                countBucket[count] = new ArrayList<Integer>();
            countBucket[count].add(nums[i]);
        }
        
        int i = countBucket.length-1;
        while (i >= 0 && res.size() < k) {
            if (countBucket[i] != null) {
                res.addAll(countBucket[i]); 
            }
            i--;
        }
        return res;