手写算法:回旋镖的数量

447. 回旋镖的数量open in new window

解题思路

  1. 欧式距离:表示的是点与点的坐标值之间相减的平方。A 点(x1, y1), B 点(x2, y2),这两点之间的欧式距离为:(x1 - x2)^2 + (y1 - y2)^2

  2. 回旋镖代表,例如以 A 点为基准,B 点到 A 点与 C 点到 A 点的欧式距离相等,那么就可以说是形成了回旋镖。

  3. 回旋镖计算公式:num * (num - 1)。 计算公式不知道怎么推算出来的

官方参考答案open in new window

var numberOfBoomerangs = function(points) {
  let result = 0;
  for (const p of points) {
    let map = new Map();
    for (const q of points) {
      const dis = Math.pow(p[0] - q[0], 2) + Math.pow(p[1] - q[1], 2);
      map.set(dis, (map.get(dis) || 0) + 1);
    }

    for (const count of map.values()) {
      result += count * (count - 1);
    }
  }
  return result;
};

手写题:实现 Trim<T>

43. 请实现 Trimopen in new window

  1. T extends U ? X : Y; ==> 如果 T 包含的类型是 U 包含的类型的‘子集’,那么取 X,否则取 Y

  2. infer 类型推断

type Unpacked<T> = T extends (infer U)[] ? U : T; ==> 如果 T 包含 U 数组的子集,那么取 U,否则取 Y

看几个例子

type T0 = Unpacked<string[]>; // string

type T0 = Unpacked<string>; // string
type Space = ' ' | '\n';
type Trim<T extends string> =
T extends `${Space}${infer U}` ? Trim<U>
: T extends `${infer U}${Space}` ? Trim<U> : T;
Last Updated:
Contributors: kk