leetcode 457 Circular Array Loop

You are given a circular array nums
of positive and negative integers. If a number k at an index is positive, then move forward k steps. Conversely, if it’s negative (-k), move backward k steps. Since the array is circular, you may assume that the last element’s next element is the first element, and the first element’s previous element is the last element.
Determine if there is a loop (or a cycle) in nums
. A cycle must start and end at the same index and the cycle’s length > 1. Furthermore, movements in a cycle must all follow a single direction. In other words, a cycle must not consist of both forward and backward movements.
Example 1:
1 | Input: [2,-1,1,2,2] |
Example 2:
1 | Input: [-1,2] |
Example 3:
1 | Input: [-2,1,-1,-2,-2] |
Note:
- -1000 ≤ nums[i] ≤ 1000
- nums[i] ≠ 0
- 1 ≤ nums.length ≤ 5000
遍历nums,对每一个nums[i]开始循环遍历他的下一跳。
中断条件包括:
- 当这一跳的方向和初始的方向不一致,设初始的数为num,当前这一跳的数为nums[i],那么当num*nums[i] <=0时,中断。
- 当这一跳调到自己时,中断。即nums[i] % len(nums) == 0时,中断。
- 当这一跳曾经跳过时,中断。在跳的过程中,我们用标记来标注跳过的位置,如果当前这一跳被标记上跳过了,那么中断。
1 | class Solution(object): |