469. Convex Polygon

来源:互联网 发布:图片怎么上传到淘宝网 编辑:程序博客网 时间:2024/06/07 15:29

Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition).

Note:

  1. There are at least 3 and at most 10,000 points.
  2. Coordinates are in the range -10,000 to 10,000.
  3. 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: TrueExplanation:

Example 2:

[[0,0],[0,10],[10,10],[10,0],[5,5]]Answer: FalseExplanation:
这道题开始没有思路,看了这篇博客:Orientation of 3 ordered points。这篇博客里用的是p1p2,p2p3的组合,如果出现全是直角的情况,(y2 - y1)*(x3 - x2) - (y3 - y2)*(x2 - x1)会恒等于0导致算法失败。所以在我们的算法里,用p1p2,p1p3的组合,这种组合只有在p1p2p3成一条直线的时候才会等于0,但是题目中说了不会给这样的情况,给的店必然能组成一个多边形。还有一点要注意,如果用前后状态相乘是否小于0来判断前后状态是不是相反的,要防止curr * last < 0溢出。代码如下:

public class Solution {    public boolean isConvex(List<List<Integer>> points) {        int len = points.size();        int last = 0, curr = 0;        for (int i = 2; i < len + 3; i ++) {            List<Integer> point1 = points.get((i - 2) % len);            List<Integer> point2 = points.get((i - 1) % len);            List<Integer> point3 = points.get((i) % len);            curr = (point2.get(1) - point1.get(1)) * (point3.get(0) - point1.get(0)) - (point3.get(1) - point1.get(1)) * (point2.get(0) - point1.get(0));            //System.out.println(curr);            if (curr != 0) {                curr = curr / Math.abs(curr); //prevent overflow                if (curr * last < 0) {                    return false;                }                last = curr;            }        }        return true;    }}

0 0