• 347. Top K Frequent Elements 出现频率最高的k个元素


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

    For 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.
    例如,给定[1,1,1,2,2,3]和k = 2,返回[1,2]。
    注意:
    你可以假设k总是有效的,1≤k≤唯一元素的个数。
    你的算法的时间复杂度必须比O(n log n)好,其中n是数组的大小。
    1. /**
    2. * @param {number[]} nums
    3. * @param {number} k
    4. * @return {number[]}
    5. */
    6. let left = (i) => 2 * i + 1;
    7. let right = (i) => 2 * (i + 1);
    8. let buildHeap = (x, less_p) => {
    9. let n = x.length;
    10. for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
    11. heapify(x, i, less_p)
    12. }
    13. }
    14. let heapify = (x, i, less_p) => {
    15. let n = x.length;
    16. while (true) {
    17. let l = left(i);
    18. let r = right(i);
    19. let smallest = i;
    20. if (l < n && less_p(x[l], x[i])) {
    21. smallest = l;
    22. }
    23. if (r < n && less_p(x[r], x[smallest])) {
    24. smallest = r;
    25. }
    26. if (smallest != i) {
    27. [x[i], x[smallest]] = [x[smallest], x[i]];
    28. i = smallest;
    29. } else {
    30. break;
    31. }
    32. }
    33. }
    34. let heapPop = (x, less_p) => {
    35. top = x[0]
    36. x[0] = x[x.length - 1];
    37. x.pop()
    38. if (x.length > 0) {
    39. heapify(x, 0, less_p)
    40. }
    41. return top
    42. }
    43. let topK = (x, k, less_p) => {
    44. let res = [];
    45. buildHeap(x, less_p);
    46. let count = x.length;
    47. for (let i = 0; i < Math.min(k, count); i++) {
    48. res.push(heapPop(x, less_p));
    49. }
    50. return res;
    51. }
    52. var topKFrequent = function (nums, k) {
    53. let MAX_HEAP = (a, b) => m[a] > m[b];
    54. let m = {};
    55. let heap = [];
    56. for (let i in nums) {
    57. let c = nums[i];
    58. !m[c] && heap.push(c);
    59. m[c] = m[c] ? ++m[c] : 1;
    60. }
    61. return topK(heap, k, MAX_HEAP);
    62. };
    63. let nums = [1, 2];
    64. let k = 2;
    65. let res = topKFrequent(nums, k);
    66. console.log(res);







  • 相关阅读:
    CSS布局口诀
    JAVA集合框架
    java接口作用及其好处
    java 输入输出类
    Java中精确计算的一个类BigDecimal
    java 集合框架
    java JSTL标签总结
    meta标签
    Java字符串使用总结
    Java集合框架使用方法
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/8111834.html
Copyright © 2020-2023  润新知