[Leetcode] 469. Convex Polygon 解题报告
来源:互联网 发布:北师珠网络教学综合 编辑:程序博客网 时间:2024/05/17 22:08
题目:
Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition).
Note:
- There are at least 3 and at most 10,000 points.
- Coordinates are in the range -10,000 to 10,000.
- 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:
思路:
一道计算几何的基础题目,上次面试Google就挂在一道计算几何题目上了。为了便于说明,我们假设多边形的顶点是呈逆时针排列的,那么该多边形是凸多边形的充要条件是:对于多边形的任何一条边,其下一条边必须是不朝右拐的(可以向左拐,也可以不拐)。那么如何判断下一条边是不朝右拐呢?假设假设当前边形成的向量是v1,下一条边形成的向量是v2,那么v2不朝右拐的充要条件是v1 x v2 >= 0,也就是它们形成的有向三角形的面积大于等于0,符合右手法则。
对于多边形顶点呈顺时针排列的情况,判断方式刚好相反。该算法的时间复杂度是O(n),空间复杂度是O(1)。
代码:
class Solution {public: bool isConvex(vector<vector<int>>& points) { for (long i = 0, n = points.size(), prev = 0, cur; i < n; ++i) { cur = det2({points[i], points[(i + 1 )% n], points[(i + 2) % n]}); if (cur != 0) { if (cur * prev < 0) { return false; } else { prev = cur; } } } return true; }private: long det2(const vector<vector<int>>& A) { return (A[1][0]-A[0][0])*(A[2][1]-A[0][1]) - (A[1][1]-A[0][1])*(A[2][0]-A[0][0]); }};
阅读全文
0 0
- [Leetcode] 469. Convex Polygon 解题报告
- 469. Convex Polygon
- 469. Convex Polygon
- 469. Convex Polygon
- LeetCode 解题报告索引
- [LeetCode]Permutations,解题报告
- Leetcode Triangle 解题报告
- [LeetCode]Anagrams,解题报告
- leetCode解题报告
- [LeetCode]Candy, 解题报告
- 【LeetCode】Candy 解题报告
- 【LeetCode】Triangle 解题报告
- 【LeetCode】Permutations 解题报告
- LeetCode 解题报告 LinkedListCycleII
- LeetCode 解题报告 Candy
- 【LeetCode】Anagrams 解题报告
- 【LeetCode】Combinations 解题报告
- 【LeetCode】Subsets 解题报告
- python yield理解
- macbook使用ZOC连接Linux云主机
- c/c++在windows下获取时间和计算时间差的几种方法总结
- Android签名二: package.xml packagelist.xml分析
- 酢浆草2017记录
- [Leetcode] 469. Convex Polygon 解题报告
- 数据库设计原则(一)
- My Calendar II问题及解法
- python中re模块基础用法(正则)
- resultMap中两张表id字段相同,数据查询异常解决
- #面向对象的六大原则
- 编写函数,将一维数组(array[10])的元素从小到大排序,在主函数中读入数组的元素
- strtus2里的struts.xml的配置
- html css 右侧固定 左边自适应样式