Middle-题目123:335. Self Crossing

原创 2016年05月31日 20:16:23

题目原文:
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[0]米,再向左走x[1]米,再向下走x[2]米,再向下走x[3]米,以此类推的逆时针走,判断运动轨迹是否相交。
题目分析:
参考了discuss中一位大神的算法,解释如下:
首先,只走3步是不可能产生交点的,所以考虑走4步,走5步,走6步产生交点的情况,而走7步与走5步是等价的,所以只需讨论三种情况即可。(画图太渣,还是传手写照片吧)
这里写图片描述
需注意情况3中第一个条件是没有等号的,如果取等则变为情况2!
源码:(language:java)

public class Solution {
    public boolean isSelfCrossing(int[] x) {
        for(int i=3;i<x.length;i++){
            if(i>=3&&x[i]>=x[i-2]&&x[i-1]<=x[i-3])
                return true;
            if(i>=4&&x[i-1]==x[i-3]&&x[i-2]<=x[i]+x[i-4])
                return true;
            if(i>=5&&x[i-2]>x[i-4]&&x[i-1]<=x[i-3]&&x[i-1]+x[i-5]>=x[i-3]&&x[i]+x[i-4]>=x[i-2])
                return true;
        }
        return false;
    }
}

成绩:
0ms,beats 43.49%,众数0ms,56.51%
Cmershen的碎碎念:
本算法简洁优美,堪称绝妙!还有,高中的平面向量还记得么~~

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

[leetcode] 335. Self Crossing 解题报告

题目链接:https://leetcode.com/problems/self-crossing/ You are given an array x of n positive number...

leedCode 335 Self Crossing

问题描述: You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] met...

LeetCode335 Self Crossing Java

题目 You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres ...

leetcode_335 Self Crossing

题意分析: 定一个数组x,代表行走的距离,最初的方向是北,每走一步就按逆时针顺序变化方向(北,西,南,东)要求只遍历一次x,并且用O(1)的存储空间,判断走过的路径是否交叉。 解题思路: 方法1:分南...

LeetCode 335. Self Crossing(贪吃蛇)

原题网址:https://leetcode.com/problems/self-crossing/ You are given an array x of n positive numbers. ...

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 th...

LeetCode hard 335. Self Crossing

因为老师这周在讲比较形而上的NP问题,所以就让我们随便选题了,果断我就真随便选了,看了tag后才发现这是一道数学题,还是一道几何题,好吧,没这么严重,估计小学生都能想出一点东西来,直接上题吧 ---...

Self Crossing

You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to t...

Self Crossing

You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to ...

Middle-题目33:300. Longest Increasing Subsequence

题目原文: Given an unsorted array of integers, find the length of longest increasing subsequence.For ex...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)