469. Convex Polygon

50 篇文章 0 订阅

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: True

Explanation:

Example 2:

[[0,0],[0,10],[10,10],[10,0],[5,5]]

Answer: False

Explanation:
这道题开始没有思路,看了这篇博客: 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值