https://leetcode.com/problems/convex-polygon/description/
给定一个多边形的nnn个顶点坐标组成的数组AAA,题目保证按所给顺序遍历这些顶点可以得到一个nnn边形,问这个多边形是不是凸的。
看一下A[0]A[1]⃗×A[1]A[2]⃗\vec{A[0]A[1]}\times \vec{A[1]A[2]}A[0]A[1]×A[1]A[2]的符号(即指向纸面外还是内),然后依次计算A[k]A[k+1]⃗×A[k+1]A[k+2]⃗\vec{A[k]A[k+1]}\times \vec{A[k+1]A[k+2]}A[k]A[k+1]×A[k+1]A[k+2]的符号,如果其中一个符号与A[0]A[1]⃗×A[1]A[2]⃗\vec{A[0]A[1]}\times \vec{A[1]A[2]}A[0]A[1]×A[1]A[2]不同,则说明发生了凹陷,从而不是凸多边形。代码如下:
class Solution {public:bool isConvex(vector>& ps) {int n = ps.size();// 注意,最后还需要判断最后两个点和起始点的向量叉乘。ps.push_back(ps[0]);ps.push_back(ps[1]);int p = cross(ps[0], ps[1], ps[1], ps[2]) > 0 ? 1 : -1;for (int i = 0; i < n; i++)if (cross(ps[i], ps[i + 1], ps[i + 1], ps[i + 2]) * p < 0) return false;return true;}int cross(vector& a, vector& b, vector& c, vector& d) {int x1 = b[0] - a[0], x2 = d[0] - c[0];int y1 = b[1] - a[1], y2 = d[1] - c[1];return x1 * y2 - x2 * y1;}
};
时间复杂度O(n)O(n)O(n),空间O(1)O(1)O(1)。
下一篇:字符串的转换路径问题