zoukankan      html  css  js  c++  java
  • [Swift]LeetCode335. 路径交叉 | Self Crossing

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/10261989.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    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:

    Input: [2,1,1,2]
    
    ?????
    ?   ?
    ???????>
        ?
    
    Input: true 
    Explanation: self crossing
    

    Example 2:

    Input: [1,2,3,4]
    
    ????????
    ?      ?
    ?
    ?
    ?????????????>
    
    Output: false 
    Explanation: not self crossing
    

    Example 3:

    Input: [1,1,1,1]
    
    ?????
    ?   ?
    ?????>
    
    Output: true 
    Explanation: self crossing

    给定一个含有 n 个正数的数组 x。从点 (0,0) 开始,先向北移动 x[0] 米,然后向西移动 x[1] 米,向南移动 x[2] 米,向东移动 x[3] 米,持续移动。也就是说,每次移动后你的方位会发生逆时针变化。

    编写一个 O(1) 空间复杂度的一趟扫描算法,判断你所经过的路径是否相交。

    示例 1:

    输入: [2,1,1,2]
    
    ?????
    ?   ?
    ???????>
        ?
    
    输出: true 
    解释: 路径交叉了
    

    示例 2:

    输入: [1,2,3,4]
    
    ????????
    ?      ?
    ?
    ?
    ?????????????>
    
    输出: false 
    解释: 路径没有相交
    

    示例 3:

    输入: [1,1,1,1]
    
    ?????
    ?   ?
    ?????>
    
    输出: true 
    解释: 路径相交了

    8ms
     1 class Solution {
     2     func isSelfCrossing(_ x: [Int]) -> Bool {
     3         if x.count < 4 {
     4             return false
     5         }
     6         let c = x.count
     7         for i in 0..<c {
     8             if (i + 3 < c && x[i] >= x[i + 2] && x[i + 1] <= x[i + 3]) {
     9                 return true
    10             }
    11             if (i + 4 < c && x[i + 1] == x[i + 3] && x[i] + x[i + 4] >= x[i + 2]) {
    12                 return true
    13             }
    14             if (i + 5 < c && x[i] < x[i + 2] && x[i + 4] < x[i + 2] && x[i + 2] <= x[i] + x[i + 4] && x[i + 1] < x[i + 3] && x[i + 3] <= x[i + 1] + x[i + 5]) {
    15                 return true
    16             }
    17         }
    18         return false
    19     }
    20 }
  • 相关阅读:
    C#文件拖放至窗口的ListView控件获取文件类型
    android内存释放处理
    赵雅智_运用Bitmap和Canvas实现图片显示,缩小,旋转,水印
    POJ 3070 Fibonacci 矩阵高速求法
    poj 3261 后缀数组 找反复出现k次的子串(子串能够重叠)
    Codeforces Round #313 C. Gerald&#39;s Hexagon(放三角形)
    HTTP服务端JSON服务端
    iPad popView封装
    OpenCv 人脸检測的学习
    《深入理解java虚拟机》:类的初始化
  • 原文地址:https://www.cnblogs.com/strengthen/p/10261989.html
Copyright © 2011-2022 走看看