LeetCode 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.json

Example 1:数组

Given x = ,
?????
?   ?
???????>
    ?

Return true (self crossing)[2, 1, 1, 2]

Example 2:spa

Given x = ,
????????
?      ?
?
?
?????????????>

Return false (not self crossing)
[1, 2, 3, 4]

 

Example 3:code

Given x = ,
?????
?   ?
?????>

Return true (self crossing)[1, 1, 1, 1]

题意概述:blog

给定一个大小为n的正实数数组,表明一条路径,路径由向北,向西,向南,向东组成,判断这条路径是否自交,要求额外空间为O(1)it

算法分析:io

若是去除了题目要求的额外空间复杂度为O(1)的条件,这题就变得很是简单,解法也显而易见,只要记录下这条路径上全部的点就可判断是否自交,可是这样作是O(n)的。因此要对题目进行分析,既然题目要求让咱们考虑是否自交,那么思考的入手点应定为如何定义自交,仔细思考下能够发现自交只分为如下三种状况,而无其余可能:ast

  ①涉及四条边的相交;class

  ②涉及五条边的重合;

  ③涉及六条边的相交;

如下为三种相交图:

 

所以若是发生某一条边相交,它仅涉及当前边的前三到五条边,所以得出如下代码,算法复杂度为O(n),额外空间复杂度为O(1):

class Solution {
    public boolean isSelfCrossing(int[] x) {
        int length = x.length;
        for(int i=3;i<length;i++){
            if(x[i]-x[i-2]>=0&&x[i-1]-x[i-3]<=0){
                return true;
            }
            if(i>=4&&x[i-1]==x[i-3]&&x[i-2]>=x[i-4]&&x[i]>=x[i-2]-x[i-4]){
                return true;
            }
            if(i>=5&&x[i-2]>=x[i-4]&&x[i-3]>=x[i-5]&&x[i]>=x[i-2]-x[i-4]&&x[i-1]>=x[i-3]-x[i-5]&&x[i-1]<=x[i-3]){
                return true;
            }
        }
        return false;
    }
}
相关文章
相关标签/搜索