Skip to content
本页目录

查找热点数据

问题描述

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按任意顺序返回答案。

  • 1 <= nums.length <= 10^5
  • k 的取值范围是 [1, 数组中不相同的元素的个数]
  • 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的

你所设计算法的时间复杂度必须优于 O(n log n) ,其中 n 是数组大小。

示例 1

输入: nums = [1,1,1,2,2,3], k = 2

输出: [1,2]

示例 2

输入: nums = [1], k = 1

输出: [1]

代码实现

javascript
function solution(nums, k) {
  // Please write your code here
  let map = {}
  const arr = []
  for (let num of nums) {
    if (map[num]) {
      map[num] = map[num] + 1
    } else {
      map[num] = 1
    }
  }
  for (let num in map) {
    arr.push([num, map[num]])
  }
  const res = arr.sort((a, b) => b[1] - a[1]).slice(0, k);
  console.log(res)
  return res.map(i => i[0]).join(',')
}

function main() {
  //  You can add more test cases here
  console.log(solution([1, 1, 1, 2, 2, 3], 2) === "1,2");
  console.log(solution([1], 1) === "1");
}

main();
查找热点数据 has loaded