js(81)~[347] 前 K 个高频元素

105 阅读3分钟

力扣本题传送门

这个题跟我之前写的js(65)~[692] 前K个高频单词,基本上一模一样,但是我觉得上一次看的写法不是和好理解,所以又看了很多个解析,找到了一个更好力理解的方法,本来是准备把它改造成一个通用的又没哟改造成功
先上正确代码

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var topKFrequent = function(nums, k) {
  const map = new Map();
  
  for(const num of nums) {
    map.set(num, (map.get(num) || 0) + 1);
  }

  // 创建小顶堆
  const priorityQueue = new PriorityQueue((a, b) => a[1] - b[1]);

  // entry 是一个长度为2的数组,0位置存储key,1位置存储value
  for (const entry of map.entries()) {
    priorityQueue.push(entry);
    if (priorityQueue.size() > k) {
      priorityQueue.pop();
    }
  }

  const ret = [];

  for(let i = priorityQueue.size() - 1; i >= 0; i--) {
    ret[i] = priorityQueue.pop()[0];
  }

  return ret;
};


function PriorityQueue(compareFn) {
  this.compareFn = compareFn;
  this.queue = [];
}

// 添加
PriorityQueue.prototype.push = function(item) {
  this.queue.push(item);
  let index = this.queue.length - 1;
  let parent = Math.floor((index - 1) / 2);
  // 上浮
  while(parent >= 0 && this.compare(parent, index) > 0) {
    // 交换
    [this.queue[index], this.queue[parent]] = [this.queue[parent], this.queue[index]];
    index = parent;
    parent = Math.floor((index - 1) / 2);
  }
}

// 获取堆顶元素并移除
PriorityQueue.prototype.pop = function() {
  const ret = this.queue[0];

  // 把最后一个节点移到堆顶
  this.queue[0] = this.queue.pop();

  let index = 0;
  // 左子节点下标,left + 1 就是右子节点下标
  let left = 1;
  let selectedChild = this.compare(left, left + 1) > 0 ? left + 1 : left;

  // 下沉
  while(selectedChild !== undefined && this.compare(index, selectedChild) > 0) {
    // 交换
    [this.queue[index], this.queue[selectedChild]] = [this.queue[selectedChild], this.queue[index]];
    index = selectedChild;
    left = 2 * index + 1;
    selectedChild = this.compare(left, left + 1) > 0 ? left + 1 : left;
  }

  return ret;
}

PriorityQueue.prototype.size = function() {
  return this.queue.length;
}

// 使用传入的 compareFn 比较两个位置的元素
PriorityQueue.prototype.compare = function(index1, index2) {
  if (this.queue[index1] === undefined) {
    return 1;
  }
  if (this.queue[index2] === undefined) {
    return -1;
  }

  return this.compareFn(this.queue[index1], this.queue[index2]);
}

下面是我改造的代码,失败的,除此我还有按照之前我经常写的大顶堆和小顶堆尝试解决本题,也是没有成功,代码在最后

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
 var topKFrequent = function(nums, k) {
  const map = new Map();
  
  for(const num of nums) {
    map.set(num, (map.get(num) || 0) + 1);
  }

  // 创建小顶堆
  const priorityQueue = new PriorityQueue();

  // entry 是一个长度为2的数组,0位置存储key,1位置存储value
  for (const entry of map.entries()) {
    priorityQueue.push(entry);
    if (priorityQueue.size() > k) {
      priorityQueue.pop();
    }
  }

  const ret = [];

  for(let i = priorityQueue.size() - 1; i >= 0; i--) {
    ret[i] = priorityQueue.pop()[0];
  }

  return ret;
};

const cmp = (a, b) => a[1] < b[1];
function PriorityQueue(compareFn = cmp) {
  this.compare = compareFn;
  this.queue = [];
}

// 添加
PriorityQueue.prototype.push = function(item) {
  this.queue.push(item);
  let index = this.queue.length - 1;
  let parent = Math.floor((index - 1) / 2);
  // 上浮
  while(parent >= 0 && this.compare(this.queue[parent], this.queue[index]) ) {
    // 交换
    [this.queue[index], this.queue[parent]] = [this.queue[parent], this.queue[index]];
    index = parent;
    parent = Math.floor((index - 1) / 2);
  }
}

// 获取堆顶元素并移除
PriorityQueue.prototype.pop = function() {
  const ret = this.queue[0];

  // 把最后一个节点移到堆顶
  this.queue[0] = this.queue.pop();

  let index = 0;
  // 左子节点下标,left + 1 就是右子节点下标
  let left = 1;
  let selectedChild = this.compare(this.queue[left], this.queue[left+ 1]) 
   ? left : left + 1;

  // 下沉
  while(selectedChild !== undefined && this.compare(this.queue[selectedChild],this.queue[index] ) ) {
    // 交换
    [this.queue[index], this.queue[selectedChild]] = [this.queue[selectedChild], this.queue[index]];
    index = selectedChild;
    left = 2 * index + 1;
    selectedChild = this.compare(this.queue[left], this.queue[left+ 1])  ? left  : left+1;
  }

  return ret;
}

PriorityQueue.prototype.size = function() {
  return this.queue.length;
}

// 使用传入的 compareFn 比较两个位置的元素
// PriorityQueue.prototype.compare = function(index1, index2) {
//   if (this.queue[index1] === undefined) {
//     return 1;
//   }
//   if (this.queue[index2] === undefined) {
//     return -1;
//   }

//   return this.compareFn(this.queue[index1], this.queue[index2]);
// }


另外一种错误代码

/*
 * @lc app=leetcode.cn id=347 lang=javascript
 *
 * [347] 前 K 个高频元素
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var topKFrequent = function (nums, k) {
	let map = new Map();
	let heap = [];
	// 1 生成一个map先统计nums每个数出现的频次
	nums.forEach(item => {
		map.has(item) ? map.set(item, map.get(item) + 1) : map.set(item, 1)
	})
	const minHeap = new Heap();
	console.log(minHeap);
	for (const item of map.entries()) {
		minHeap.insert(item);
		console.log(minHeap.arr.length,'k', k);
		if (minHeap.arr.length > k) {
			minHeap.pop();
		}
	}

	console.log(minHeap, '-----', minHeap.arr)
	const res = [];

  for(let i = minHeap.arr.length - 1; i >= 0; i--) {
    res[i] = minHeap.pop()[0];
  }

  return res;

};

const swap = (arr, i, j) => ([arr[i], arr[j]] = [arr[j], arr[i]]);
const defaultCmp = (a, b) => (a[1] < b[1]);
class Heap {
	constructor(cmp = defaultCmp) {
		this.arr = [];
		this.cmp = cmp;
	}

	insert(v) {
		this.arr.push(v);
		let i = this.arr.length - 1;
		while (i) {
			let parent = i - 1 >> 1;
			if (this.cmp(i, parent)) {
				swap(this.arr, i, parent)
				i = parent;
			}
		}
	}

	pop() {
		const len = this.arr.length;

		swap(this.arr, 0, i);
		const res = this.arr.pop();

		let i = 0;
		let exchange = 2 * i + 1;
		while (exchange < len) {
			let r = 2 * i + 2;
			if (r < len && this.cmp(arr[r], arr[exchange])) {
				exchange = r;
			}

			if (this.cmp(exchange, i)) {
				swap(this.arr, i, exchange);

				i = exchange;
				exchange = 2 * i + 1;
			} else {
				break;
			}

		}

		return res;
	}

}
// @lc code=end