跳到主要内容

414.第三大的数

链接:414.第三大的数
难度:Easy
标签:数组、排序
简介:给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以 字符串形式返回小数 。

题解 1 - typescript

  • 编辑时间:2021-10-06
  • 执行用时:84ms
  • 内存消耗:40.7MB
  • 编程语言:typescript
  • 解法介绍:堆。
class Heap<T = number> {
private arr: T[] = [];
get isEmpty() {
return this.size === 0;
}
get size() {
return this.arr.length;
}
get top() {
return this.arr[0];
}
constructor(private compare: (t1: T, t2: T) => number) {}
add(num: T): void {
this.arr.push(num);
this.shiftUp(this.size - 1);
}
remove(): T {
const num = this.arr.shift()!;
if (this.size) {
this.arr.unshift(this.arr.pop()!);
this.shiftDown(0);
}
return num;
}
private shiftUp(index: number): void {
if (index === 0) return;
const parentIndex = (index - 1) >> 1;
if (this.compare(this.arr[index], this.arr[parentIndex]) > 0) {
[this.arr[index], this.arr[parentIndex]] = [this.arr[parentIndex], this.arr[index]];
this.shiftUp(parentIndex);
}
}
private shiftDown(index: number): void {
let childrenIndex = index * 2 + 1;
if (childrenIndex > this.size - 1) return;
if (
childrenIndex + 1 <= this.size - 1 &&
this.compare(this.arr[childrenIndex + 1], this.arr[childrenIndex]) > 0
) {
childrenIndex++;
}
if (this.compare(this.arr[childrenIndex], this.arr[index]) > 0) {
[this.arr[childrenIndex], this.arr[index]] = [this.arr[index], this.arr[childrenIndex]];
this.shiftDown(childrenIndex);
}
}
*[Symbol.iterator](): IterableIterator<T> {
for (const t of this.arr) {
yield t;
}
}
}
function thirdMax(nums: number[]): number {
const heap = new Heap((t1, t2) => t1 - t2);
[...new Set(nums)].forEach(num => heap.add(num));
if (heap.size < 3) return heap.remove();
let ans = 0;
for (let i = 0; i < 3; i++) ans = heap.remove();
return ans;
}

题解 2 - typescript

  • 编辑时间:2021-10-06
  • 执行用时:80ms
  • 内存消耗:40.1MB
  • 编程语言:typescript
  • 解法介绍:排序。
function thirdMax(nums: number[]): number {
nums = [...new Set(nums)].sort((a, b) => b - a);
return nums[2] ?? nums[0];
}