469. Convex Polygon
Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition).
Note:
There are at least 3 and at most 10,000 points.
Coordinates are in the range -10,000 to 10,000.
You may assume the polygon formed by given points is always a simple polygon (Simple polygon definition). In other words, we ensure that exactly two edges intersect at each vertex, and that edges otherwise don't intersect each other.
Example 1:
[[0,0],[0,1],[1,1],[1,0]]
Answer: True
Explanation:
Example 2:
[[0,0],[0,10],[10,10],[10,0],[5,5]]
Answer: False
Explanation:
int crossProduct(const vector<int>& A, const vector<int>& B, const vector<int>& C) {
int BAx = B[0] - A[0];
int BAy = B[1] - A[1];
int CBx = C[0] - B[0];
int CBy = C[1] - B[1];
return BAx * CBy - BAy * CBx;
}
bool isConvex(vector<vector<int>>& points) { // time: O(n); space: O(1)
int n = points.size(), j, k, cross;
bool positive_cross = false, negative_cross = false;
for (int i = 0; i < n; ++i) {
j = (i + 1) % n;
k = (j + 1) % n;
cross = crossProduct(points[i], points[j], points[k]);
if (cross > 0) positive_cross = true;
else if (cross < 0) negative_cross = true;
if (positive_cross && negative_cross) return false;
}
return true;
}
Last updated
Was this helpful?