题目链接:https://leetcode-cn.com/problems/circular-array-loop/
执行用时:72 ms, 在所有 Swift 提交中击败了100.00%的用户
内存消耗:13.5 MB, 在所有 Swift 提交中击败了100.00%的用户
快慢指针终会相遇,参考了官方题解
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { func circularArrayLoop(_ nums: [Int]) -> Bool { func next(cur: Int) -> Int{ return ((cur+nums[cur])%n + n) % n } let n = nums.count var slow = 0,fast = 0 for i in 0 ..< n { slow = i fast = next(cur: slow) while nums[fast]*nums[i] > 0 && nums[next(cur: fast)] * nums[i] > 0 { if fast == slow { if slow == next(cur: slow) { break } return true } slow = next(cur: slow) fast = next(cur: next(cur: fast)) } } return false } }
|