Shu-How Zの小窝

Loading...

LeetCode:347.前K个高频元素

LeetCode:347.前K个高频元素

var topKFrequent = function(nums, k) {
    let map=new Map();
    let arr=[...new Set(nums)]
    nums.forEach(item=>{
        if(map.has(item)){
            map.set(item,map.get(item)+1)
        }else{
            map.set(item,1)
        }
    })
    return arr.sort((a,b)=>map.get(b)-map.get(a)).slice(0,k)
};

class MinHeap {
    constructor() {
      this.heap = []
      this.len = 0
    }
    size() {
      return this.len
    }
    push(val) {
      this.heap[++this.len] = val
      this.swin(this.len)
    }
  
    pop() {
      const ret = this.heap[1]
      this.swap(1, this.len--)
      this.heap[this.len + 1] = null
      this.sink(1)
      return ret
    }
    swin(ind) {
      while (ind > 1 && this.less(ind, parseInt(ind / 2))) {
        this.swap(ind, parseInt(ind / 2))
        ind = parseInt(ind / 2)
      }
    }
    sink(ind) {
      while (ind * 2 <= this.len) {
        let j = ind * 2
        if (j < this.len && this.less(j + 1, j)) j++
        if (this.less(ind, j)) break
        this.swap(ind, j)
        ind = j
      }
    }
    top() {
      return this.heap[1]
    }
    isEmpty() {
      return this.len === 0
    }
  
    swap(i, j) {
      [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]
    }
    less(i, j) {
      return this.heap[i].val < this.heap[j].val
    }
    getHeap() {
      return this.heap
    }
  }
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var topKFrequent = function(nums, k) {
    let map=new Map();
    nums.forEach(item=>{
        if(map.has(item)){
            map.set(item,map.get(item)+1)
        }else{
            map.set(item,1)
        }
    })
    let h=new MinHeap();
    map.forEach((val,key)=>{
        h.push({val,key});
        if(h.size()>k) h.pop();
    })
    return h.heap.filter(item=>item&&item.val).map(item=>item.key);
};

posted @ 2025-01-14 22:39  KooTeam  阅读(11)  评论(0)    收藏  举报