[Leetcode 1037] Valid Boomerang

原题说明

boomerang is a set of 3 points that are all distinct and not in a straight line.

Given a list of three points in the plane, return whether these points are a boomerang.

 

Example 1:

Input: [[1,1],[2,3],[3,2]]
Output: true

Example 2:

Input: [[1,1],[2,2],[3,3]]
Output: false

 

Note:

  1. points.length == 3
  2. points[i].length == 2
  3. 0 <= points[i][j] <= 100

解题思路

判断AB,AC斜率是否相同,如果相同则在一条线上
注意用乘法好过除法, 因为不用判断分母为0了。
面试时要考虑特殊情况,比如两个点重合是否算同线 (本题是distinct的点,所以不用考虑)

示例代码 (cpp)

1
2
3
4
5
6
class Solution {
public:
bool isBoomerang(vector<vector<int>>& points) {
return (points[0][0] - points[1][0]) * (points[0][1] - points[2][1]) != (points[0][0] - points[2][0]) * (points[0][1] - points[1][1]);
}
};

示例代码 (java)

1
2
3
4
5
class Solution {
public boolean isBoomerang(int[][] p) {
return (p[0][0] - p[1][0]) * (p[0][1] - p[2][1]) != (p[0][0] - p[2][0]) * (p[0][1] - p[1][1]);
}
}

示例代码 (python)

1
2
3
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
return (points[0][0] - points[1][0]) * (points[0][1] - points[2][1]) != (points[0][0] - points[2][0]) * (points[0][1] - points[1][1])

复杂度分析

时间复杂度: O(1)
空间复杂度: O(1)

归纳总结

我们在Youtube上更新了视频讲解,欢迎关注!

------ 关注公众号:猩猩的乐园 ------