首页 技术 正文
技术 2022年11月8日
0 收藏 302 点赞 1,094 浏览 1546 个字

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.

Example 1:

Given x = [2, 1, 1, 2],
┌───┐
│ │
└───┼──>
│Return true (self crossing)

Example 2:

Given x = [1, 2, 3, 4],
┌──────┐
│ │


└────────────>Return false (not self crossing)

Example 3:

Given x = [1, 1, 1, 1],
┌───┐
│ │
└───┼>Return true (self crossing)

这道题给了我们一个一位数组,每个数字是个移动量,按照上左下右的顺序来前进每一个位移量,问我们会不会和之前的轨迹相交,而且限定了常量的空间复杂度,我立马想到了贪吃蛇游戏,但是这条蛇不会自动向前移动哈。言归正传,这题我不会,参考的网上大神们的解法,实际上相交的情况只有以下三种情况:

     x()
┌───┐
x()│ │x()
└───┼──>
x()│

第一类是第四条边和第一条边相交的情况,需要满足的条件是第一条边大于等于第三条边,第四条边大于等于第二条边。同样适用于第五条边和第二条边相交,第六条边和第三条边相交等等,依次向后类推的情况…

      x()
┌──────┐
│ │x()
x()│ ^
│ │x()
└──────│
x()

第二类是第五条边和第一条边重合相交的情况,需要满足的条件是第二条边和第四条边相等,第五条边大于等于第三条边和第一条边的差值,同样适用于第六条边和第二条边重合相交的情况等等依次向后类推…

      x()
┌──────┐
│ │x()
x()│ <│────│
│ x()│x()
└───────────│
x()

第三类是第六条边和第一条边相交的情况,需要满足的条件是第四条边大于等于第二条边,第三条边大于等于第五条边,第五条边大于等于第三条边和第一条边的差值,第六条边大于等于第四条边和第二条边的差值,同样适用于第七条边和第二条边相交的情况等等依次向后类推…

那么根据上面的分析,我们不难写出代码如下:

class Solution {
public:
bool isSelfCrossing(vector<int>& x) {
for (int i = ; i < x.size(); ++i) {
if (x[i] >= x[i - ] && x[i - ] >= x[i - ]) {
return true;
}
if (i >= && x[i-] == x[i-] && x[i] >= x[i-] - x[i-]) {
return true;
}
if (i >= && x[i-] >= x[i-] && x[i-] >= x[i-] && x[i-] >= x[i-] - x[i-] && x[i] >= x[i-] - x[i-]) {
return true;
}
}
return false;
}
};

参考资料:

https://leetcode.com/discuss/88054/java-oms-with-explanation

https://leetcode.com/discuss/88196/re-post-2-o-n-c-0ms-solutions

LeetCode All in One 题目讲解汇总(持续更新中…)

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,985
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,501
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,345
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,128
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,763
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,839