前K个常用元素

时间:2018-11-03 07:26:15

标签: java algorithm data-structures

我正在处理一个面试问题,在给定非空整数数组的情况下,我需要返回k个最频繁的元素。

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

这是我的代码:

  public static void main(String[] args) {
    System.out.println(topKFrequent(new int[] {1, 1, 1, 2, 2, 3, 3}, 1));
  }

  private static List<Integer> topKFrequent(int[] nums, int k) {
    // freq map
    Map<Integer, Integer> freq = new HashMap<Integer, Integer>();
    for (int n : nums) {
      freq.put(n, freq.getOrDefault(n, 0) + 1);
    }
    // bucket sort on freq
    List<Integer>[] bucket = new LinkedList[nums.length + 1];
    for (int i = 0; i < bucket.length; i++)
      bucket[i] = new LinkedList<>();
    for (int key : freq.keySet()) {
      bucket[freq.get(key)].add(key);
    }
    // gather result
    List<Integer> res = new ArrayList<>();
    for (int i = bucket.length - 1; i >= 0; i--) {
      res.addAll(bucket[i]);
      if (res.size() >= k)
        break;
    }
    return res;
  }

我想检查一下此代码是否可以进行任何改进/优化?当存在多个具有相同频率的数字时,我感到困惑。在这种情况下我们该怎么办?

1 个答案:

答案 0 :(得分:0)

这部分

def joinWords(string, suffix="", postfix=""):
    return suffix + string + postfix

我会写一个循环

List<Integer>[] bucket = new LinkedList[nums.length + 1];
for (int i = 0; i < bucket.length; i++)
  bucket[i] = new LinkedList<>();
for (int key : freq.keySet()) {
  bucket[freq.get(key)].add(key);
}

在这种情况下,最后一部分

List<Integer>[] bucket = new LinkedList[nums.length + 1];
for (int key : freq.keySet()) {
  List<Integer> currentBucket = bucket[freq.get(key)];
  if (currentBucket == null) {
      currentBucket = new LinkedList<Integer>();
      bucket[freq.get(key)] = currentBucket;
  }
  currentBucket.add(key);
}

需要跳过空值

List<Integer> res = new ArrayList<>();
for (int i = bucket.length - 1; i >= 0; i--) {
  res.addAll(bucket[i]);
  if (res.size() >= k)
    break;
}