未验证 提交 48aefb34 编写于 作者: K Keqi Huang 提交者: GitHub

Create 457._Circular_Array_Loop.md

上级 8479e6b8
# 457. Circular Array Loop
**<font color=red>难度: Medium</font>**
## 刷题内容
> 原题连接
* https://leetcode.com/problems/circular-array-loop/description/
> 内容描述
```
You are given an array of positive and negative integers. If a number n at an index is positive, then move forward n steps. Conversely, if it's negative (-n), move backward n steps. Assume the first element of the array is forward next to the last element, and the last element is backward next to the first element. Determine if there is a loop in this array. A loop starts and ends at a particular index with more than 1 element along the loop. The loop must be "forward" or "backward'.
Example 1: Given the array [2, -1, 1, 2, 2], there is a loop, from index 0 -> 2 -> 3 -> 0.
Example 2: Given the array [-1, 2], there is no loop.
Note: The given array is guaranteed to contain no element "0".
Can you do it in O(n) time complexity and O(1) space complexity?
```
## 解题方案
> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******
快慢指针,
```python
class Solution(object):
def circularArrayLoop(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def get_next_idx(i):
n = len(nums)
return (i + nums[i] + n) % n
for i, val in enumerate(nums):
if val == 0:
continue
j = i
k = get_next_idx(i)
while nums[k] * val > 0 and nums[get_next_idx(k)] * val > 0:
if j == k:
if j == get_next_idx(j):
break
return True
j = get_next_idx(j)
k = get_next_idx(get_next_idx(k))
j = i
while nums[j] * val > 0:
nxt = get_next_idx(j)
nums[j] = 0
j = nxt
return False
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册