[路飞]_js算法:leetcode 692-前K个高频单词

125 阅读1分钟

leetcode 692. 前K个高频单词

问题描述: 给定一个单词列表 words 和一个整数 k ,返回前 k **个出现次数最多的单词。

返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率, 按字典顺序 排序。

 

示例 1:

输入: words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i""love" 为出现次数最多的两个单词,均为2次。
    注意,按字母顺序 "i""love" 之前。

示例 2:

输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny""day" 是出现次数最多的四个单词,
    出现次数依次为 4, 3, 21 次。

思路: 建立map,算出每个单词对应的次数,然后建立堆(次数相等取排名靠前的,否则建立小顶堆),最后排序(注意次数相等,字母靠前的排名在前)

/**
 * @param {string[]} words
 * @param {number} k
 * @return {string[]}
 */
var topKFrequent = function(words, k) {
  let map=new Map();
    for(const x of words) {
      map.set(x,(map.get(x)||0)+1);
    }
   const heap=new Heap((a,b)=>{
       if(map.get(a)===map.get(b))return a>b;
    return map.get(a)<map.get(b)
      }
      );
   for(const x of map.keys()){
     heap.push(x);
     if(heap.size>k)heap.pop()
   }
   const res=heap.getData();
   const re=res.sort((a,b)=>{
       if(map.get(a)===map.get(b)){
            return a.localeCompare(b);
       }
       return map.get(b)-map.get(a)
   })
   return re;
};
//堆得实现
class Heap {
  constructor(cmp) {
      this.data = [];
      this.cmp = cmp;
  }
  get size() {
      return this.data.length;
  }
  get top() {
      return this.data[0];
  }
  getData() {
      return this.data;
  }
  swap(i, j) {
      [this.data[i], this.data[j]] = [this.data[j], this.data[i]];
  }
  // 向上冒泡
  up(i) {
      let index=this.data.length-1;
      while(index>0){
          let p=Math.floor((index-1)/2);
          if(p>=0&&this.cmp(this.data[index],this.data[p])){
              this.swap(index,p);
              index=p;
          }else{
              break;
          }
      }
  }
  // 下沉操作
  down(i) {
    if(this.data.length<2)return;
    let index=0,l=2*index+1,len=this.data.length;
    while(l<len){
      let r=l+1;
      if(r<len&&this.cmp(this.data[r], this.data[l]))l=r;
      if(this.cmp(this.data[index], this.data[l]))break;
      this.swap(index,l)
      index=l;
      l=index*2+1;
    }
  }
  push(item) {
    this.data.push(item);
    this.up();
  }
  //删除堆顶元素
  pop() {
      this.swap(0, this.data.length - 1);
      const res = this.data.pop();//已删除的元素(原来的堆顶元素)
      this.down();
      return res;
  }
}