题目描述: 给定一个按顺序连接的多边形的顶点,判断该多边形是否为凸多边形。(凸多边形的定义) 注: 顶点个数至少为 3 个且不超过 10,000。 坐标范围为 -10,000 到 10,000。 你可以假定给定的点形成的多边形均为简单多边形(简单多边形的定义)。换句话说,保证每个顶点处恰好是两条边的汇合点,并且这些边 互不相交 。
示例 1: [[0,0],[0,1],[1,1],[1,0]] 输出: True 示例 2: [[0,0],[0,10],[10,10],[10,0],[5,5]] 输出: False 方法1: 主要思路: (1)使用相邻两边组成的向量的叉积判断,若给出的多边形是凸多边形,则沿着一个方向进行叉积的计算时,各对相邻边的叉积的正负号应该是一致的,若是不一致,则不是凸多边形;
class Solution { public: bool isConvex(vector<vector<int>>& points) { bool is_negative=true;//标识相邻边的叉积的正负性 int len=points.size(); //初始判断,先找个基准,既初始的正负性的确定,为了便于后面循环的处理,这里可以先将最后的点和起始的点形成点的相邻边处理 pair<int,int> pre={points[len-1][0]-points[len-2][0],points[len-1][1]-points[len-2][1]}; pair<int,int> cur={points[0][0]-points[len-1][0],points[0][1]-points[len-1][1]}; if(pre.first*cur.second-pre.second*cur.first>0){//初始的正负性的判断 is_negative=false; } int index=1; //判断随后的各对相邻边的叉积的正负性 while(index<len){ pre=cur; cur={points[index][0]-points[index-1][0],points[index][1]-points[index-1][1]}; int tmp=pre.first*cur.second-pre.second*cur.first; if((tmp>0&&is_negative)||(tmp<0&&!is_negative)){//若是正负性不一致,则返回false return false; } ++index; } //跳出循环,说明都一致,返回true return true; } };