469. Convex Polygon
题目链接:https://leetcode.com/problems...
不会,参考这个博客的解释:
http://www.cnblogs.com/grandy...
计算三个点的法向量(叉乘),任意三个点必须同正或同负。这样判断三点组成的两边角度是否小于180。注意考虑90度的情况,这时候叉乘为0。
public class Solution {
public boolean isConvex(List<List<Integer>> points) {
int prev = 0;
int n = points.size();
for(int i = 0; i < n; i++) {
// check the angle constructed by (p0, p1) and (p0, p2)
List<Integer> p0 = points.get(i);
List<Integer> p1 = points.get((i + 1) % n);
List<Integer> p2 = points.get((i + 2) % n);
int dx1 = p0.get(0) - p1.get(0), dx2 = p0.get(0) - p2.get(0);
int dy1 = p0.get(1) - p1.get(1), dy2 = p0.get(1) - p2.get(1);
int cur = getProduct(dx1, dx2, dy1, dy2);
// product different
if((prev < 0 && cur > 0) || (prev > 0 && cur < 0)) return false;
prev = (cur == 0 ? prev : cur);
}
return true;
}
private int getProduct(int dx1, int dx2, int dy1, int dy2) {
return dx1 * dy2 - dx2 * dy1;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。