[LeetCode] Convex Polygon

469. Convex Polygon

You are given an array of points on the X-Y plane points where points[i] = [xi, yi]. The points form a polygon when joined sequentially.

Return true if this polygon is convex and false otherwise.

You may assume the polygon formed by given points is always a simple polygon. In other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don’t intersect each other.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
long long det(vector<int>& A, vector<int>& B, vector<int>& C) {
return 1ll * (B[0] - A[0]) * (C[1] - A[1]) - 1ll * (B[1] - A[1]) * (C[0] - A[0]);
}
public:
bool isConvex(vector<vector<int>>& points) {
long long last = 0, n = points.size();
for(int i = 0; i < n; i++) {
long long now = det(points[i], points[(i+1)%n], points[(i+2)%n]);
if(now) {
if(now * last < 0) return false;
last = now;
}
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/23/PS/LeetCode/convex-polygon/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.