「每日LeetCode」2022年6月8日

本文最后更新于:2023年3月19日 晚上

1037.有效的回旋镖

1037.有效的回旋镖

Category Difficulty Likes Dislikes
algorithms Easy (43.81%) 68 -

Tags
Companies
给定一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点,_如果这些点构成一个 _回旋镖 则返回 true 。
回旋镖 定义为一组三个点,这些点 各不相同不在一条直线上

示例 1:
输入:points = [[1,1],[2,3],[3,2]] 输出:true
示例 2:
输入:points = [[1,1],[2,2],[3,3]] 输出:false

提示:

  • points.length == 3
  • points[i].length == 2
  • 0 <= xi, yi <= 100

Discussion | Solution

思路

按题意先判断是否是重复的点,再和判断和其他线的连线是否是已经出现过的直线。直线和点都用 set 统计。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
* @lc app=leetcode.cn id=1037 lang=javascript
*
* [1037] 有效的回旋镖
*/

// @lc code=start
/**
* @param {number[][]} points
* @return {boolean}
*/
var isBoomerang = function (points) {
const set = new Set(),
setE = new Set();

const calculateK = ([x1, y1], [x2, y2]) => (y2 - y1) / (x2 - x1);

for (const point of points) {
const [x, y] = point;
const str = `${x},${y}`;
if (set.has(str)) return false;
for (const item of set) {
const [x2, y2] = item.split(",");
const k = calculateK([x, y], [x2, y2]);
let equation;
if (k === Infinity) {
equation = `x = ${x}`;
} else {
const b = y2 - k * x2;
equation = `y = ${k}x + ${b}`;
}
if (setE.has(equation)) return false;
setE.add(equation);
}
set.add(str);
}

return true;
};
// @lc code=end