LeetCode OJ入门初探-335. Self Crossing

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)

这道题的题目重点是寻找多少步内必然可以判断有或者没有相交。画图可知,出现相交只有4步,5步,6步的情况。因此我们每次可以对其进行判断。判断条件如下
if(x[a]>=x[c]&&x[b]<=x[d]) return true; if((x[a]+x[e]>=x[c])&&(x[b]==x[d]))
return true;
if(x[d]>=x[b]&&x[e]<=x[c]&&x[e]+x[a]>=x[c]&&x[f]+x[b]>=x[d])
return true;

注意6步的情况,判断较复杂:

class Solution {
public:
bool isSelfCrossing(vector& x) {

if(x.size()<4) return false; else { for(int i = 0;i <= x.size()-4;i++) { int a = i; int b = i+1; int c = i+2; int d = i+3; int e = i+4; int f = i+5; if((x.size()-i)>=6)
{
if(x[a]>=x[c]&&x[b]<=x[d]) return true; if((x[a]+x[e]>=x[c])&&(x[b]==x[d]))
return true;
if(x[d]>=x[b]&&x[e]<=x[c]&&x[e]+x[a]>=x[c]&&x[f]+x[b]>=x[d])
return true;
}
if((x.size()-i)==5)
{
if(x[a]>=x[c]&&x[b]<=x[d]) return true; if((x[a]+x[e]>=x[c])&&(x[b]==x[d]))
return true;
}
if((x.size()-i)==4)
{
if(x[a]>=x[c]&&x[b]<=x[d]) return true; } } } return false; } };

参考:边界判断有错误
参考:有问题

发表评论