LeetCode 335. Self Crossing|问题分类分析
来源:互联网 发布:网络红人欲猫儿 编辑:程序博客网 时间:2024/05/29 07:19
算法题目
You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west, x[2] metres to the south, x[3] metres to the east and so on. In other words, after each move your direction changes counter-clockwise.
Write a one-pass algorithm with O(1) extra space to determine, if your path crosses itself, or not.
leetcode原题链接
算法分析
这一题有O(1)的空间复杂度限制,所以不能额外开多数组来储存坐标信息,我一开始是想没加入一个顶点从重新计算前面的顶点看有没有交叉,但这样的时间复杂度是O(N^2),虽然题目没有要求时间复杂度,但是觉得这样过于暴力不优雅,应该也不是最优的解法。然后我尝试着把集中自交情况画出来,发现自交的只有三种情况。
按照这三个分类我们不难写出程序
bool isSelfCrossing(vector<int>& x) { for(int i = 0 ; i < x.size() ; i++){ if(i>=3&&x[i]>=x[i-2]&&x[i-1]<=x[i-3]) return true; if(i>=4&&x[i-1]==x[i-3]&&x[i]+x[i-4]==x[i-2]) return true; if(i>=5&&x[i-1]<x[i-3]&&x[i-1]>=x[i-3]-x[i-5]&&x[i-3]>=x[i-5]&&x[i]>=x[i-2]-x[i-4]&&x[i-2]>=x[i-4]) return true; } return false;}
0 0
- LeetCode 335. Self Crossing|问题分类分析
- [leetcode]335. Self Crossing
- leetcode 335. Self Crossing
- [LeetCode] 335. Self Crossing
- [leetcode] 335. Self Crossing
- leetcode.335. Self Crossing
- Leetcode:335. Self Crossing
- LeetCode-335.Self Crossing
- LeetCode 335. Self Crossing
- [LeetCode]335. Self Crossing
- leetcode 335. Self Crossing
- Leetcode题解:335. Self Crossing
- LeetCode hard 335. Self Crossing
- LeetCode 335. Self Crossing(贪吃蛇)
- [leetcode] 335. Self Crossing 解题报告
- [Leetcode] 335. Self Crossing 解题报告
- [LeetCode]Self Crossing
- leetcode - Self Crossing
- vb如何读取excel文件
- JavaFX学习笔记(02)(DSL构建)
- Codeforces Round #339 (Div. 2)-C. Peter and Snow Blower
- 调度算法深度解析
- Servlet之存在安全隐患的域对象
- LeetCode 335. Self Crossing|问题分类分析
- 权限管理
- Stm32 外部中断EXTI使用说明
- redis的工具类封装
- Dungeon Master(POJ2251)(C)
- hdu2955
- Centos 6 下安装 erlang 手记
- Markdown 语法的简要规则
- freeswitch时间结构体 switch_time_exp_t