public List<Integer> topKFrequent(int[] nums, int k) {
        List<Integer> res = new ArrayList<Integer>();
        if (nums == null || k <= 0) return res;

        HashMap<Integer, Integer> cntMap = new HashMap<Integer, Integer>();
        for (int n : nums) cntMap.put(n, cntMap.getOrDefault(n, 0) + 1);

        List<Integer>[] buckets = new List[nums.length + 1];
        for (int key : cntMap.keySet()) {
            int cnt = cntMap.get(key);
            if (buckets[cnt] == null) buckets[cnt] = new ArrayList<Integer>();
            buckets[cnt].add(key);
        }

        for (int i = buckets.length - 1; i >= 0; --i) {
            if (buckets[i] == null) continue;
            for (int n : buckets[i]) {
                if (res.size() < k) res.add(n);
                else break;
            }
        }
        return res;
    }