【LeetCode】Self Crossing(335)

1. Description

  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)

2. Answer
public class Solution {
    public boolean isSelfCrossing(int[] x) {
        // Check for initial four values manually.
        if (x.length < 4) {
            for (int el : x) {
                if (el == 0)
                    return true;
            }
            return false;
        }

        for (int i = 3; i < x.length; i++) {
            int cur = x[i];
            if (cur == 0)
                return true;
            // At any point of time, i-1 has to be less than i-3 in order to
            // intersect. Draw few figures to realize this.
            if (x[i - 1] <= x[i - 3]) {
                // Basic case. Straight forward intersection.
                //            ___
                //           |___|__
                //               |
                //
                if (cur >= x[i - 2]) {
                    return true;
                }
                // Special case.
                if (i >= 5) {
                    // if i-2 edge is less than i-4 th edge then it cannot
                    // intersect no matter what if i < i-2 th edge.
                    //            ____
                    //           | _  |
                    //           |__| |
                    //                |
                    if (x[i - 2] < x[i - 4])
                        continue;
                    // the intersecting case.
                    //                ____
                    //             ___|   |
                    //            |   |   |
                    //            |   |   |
                    //            |_______|
                    //
                    if ((x[i] + x[i - 4] >= x[i - 2])
                            && (x[i - 1] + x[i - 5] >= x[i - 3]))
                        return true;
                }
            }
            // equals case
            //                 ___
            //                |   |
            //                |___|
            //
            if (i >= 4)
                if (x[i - 1] == x[i - 3] && cur + x[i - 4] == x[i - 2])
                    return true;

        }
        return false;
    }
}
				
时间: 2024-08-10 21:37:07

【LeetCode】Self Crossing(335)的相关文章

【leetcode】Reverse Integer(middle)☆

Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 总结:处理整数溢出的方法 ①用数据类型转换long  或 long long ②在每次循环时先保存下数字变化之前的值,处理后单步恢复看是否相等 (比③好) ③整体恢复,看数字是否相等. 思路:注意30000这样以0结尾的数字,注意越界时返回0. 我检查越界是通过把翻转的数字再翻转回去,看是否相等. int rever

【leetcode】Happy Number(easy)

Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the

【leetcode】Word Break (middle)

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true because &

【leetcode】House Robber (middle)

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will autom

【leetcode】3Sum Closest(middle)

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2

【leetcode】Partition List(middle)

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. For example,Given 1->4->3->2

【leetcode】Dungeon Game (middle)

The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his wa

【leetcode】Rotate Image(middle)

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up:Could you do this in-place? 思路:我的思路,先沿对角线对称,再左右对称. void rotate(int **matrix, int n) { //先沿对角线对称 for(int i = 0; i < n; i++) { for(int j = 0;

【leetcode】Spiral Matrix(middle)

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example,Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. 思路:就按照螺旋矩阵的规律 用n记录旋转圈数 每