leedCode 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 moveyour direction changes counter-clockwise. Write a one-pass algorithm with O(1) extra space to determine,if your path crosses itself, or not.

(1)问题分析:

考虑所有可能否成Self Crossing的情况,共有三种情况:由4条边构成,由5条边构成,由6条边构成,如下图所示:


由于方向是逆时针90度变化的,所以构成self crossing的边是连续的,所以只需要遍历数组,考虑连续4条边 或5条边,或6条边能否封闭。

(2)写出各自的判别条件:

a) x[0]>=x[2]&&x[3]>=x[1];

b) x[1]==x[3]&&x[0]+x[4]>=x[2];

c) x[1]<x[3]&&x[4]<x[2]&&x[0]+x[4]>=x[2];

在循环时,将变量i加入到每一个索引中;

(3)完成代码

Java语言实现

public class Solution {
    public boolean isSelfCrossing(int[] x) {
        if(x.length<4){
            return false;
        }
        int[] tmp=new int[4];
        for(int i=0;i<x.length-3;i++){
            if(x[i+1]>x[i+3]){
                continue;
            }
            if(x[i+1]==x[i+3]){
                if(x[i+2]<=x[i]){
                    return true;
                   // continue;
                }
                if(i+4<x.length&&x[i+0]+x[i+4]>=x[i+2]){
                    System.out.println(i+"6");
                    return true;
                }
                continue;
            }
            if(x[i]>=x[i+2]){
                System.out.println(i+"4");
                return true;
            }
            if(i<x.length-5){
                if(x[i+0]+x[i+4]>=x[i+2]&&x[i+1]+x[i+5]>=x[i+3]&&x[i+4]<=x[i+2]){
                    System.out.println(i+"5");
                    return true;
                }
            }
            
        }
    
        return false;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值