首页 技术 正文
技术 2022年11月13日
0 收藏 686 点赞 3,176 浏览 1301 个字
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)

4th line may cross with 1st line, and so on: 5th with 2nd, …etc

5th line may cross with 1st line, and so on: 6th with 2nd, …etc

6th line also may cross with 1st line, and so on: 7th with 2nd, …etc

However, if 7th line also cross with 1st line, either of the following cases should definitely happens:

  a. 7th line cross with 2nd line

  b. 6th line cross with 1st line

  we have covered these cases.

 public class Solution {
public boolean isSelfCrossing(int[] x) {
if (x.length <= 3) return false;
for (int i=3; i<x.length; i++) {
//check if 4th line cross with the first line and so on
if (x[i]>=x[i-2] && x[i-1]<=x[i-3]) return true; //check if 5th line cross with the first line and so on
if (i >= 4) {
if (x[i-1]==x[i-3] && x[i]+x[i-4]>=x[i-2]) return true;
} //check if 6th line cross with the first line and so on
if (i >= 5) {
if (x[i-2]>=x[i-4] && x[i]>=x[i-2]-x[i-4] && x[i-1]<=x[i-3] && x[i-1]>=x[i-3]-x[i-5]) return true;
}
}
return false;
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,110
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,584
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,202
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,837
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,920