forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
circular-array-loop.py
35 lines (29 loc) · 1.02 KB
/
circular-array-loop.py
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
29
30
31
32
33
34
# Time: O(n)
# Space: O(1)
class Solution(object):
def circularArrayLoop(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def next_index(nums, i):
return (i + nums[i]) % len(nums)
for i in xrange(len(nums)):
if nums[i] == 0:
continue
slow, fast = i, i
while nums[next_index(nums, slow)] * nums[i] > 0 and \
nums[next_index(nums, fast)] * nums[i] > 0 and \
nums[next_index(nums, next_index(nums, fast))] * nums[i] > 0:
slow = next_index(nums, slow)
fast = next_index(nums, next_index(nums, fast))
if slow == fast:
if slow == next_index(nums, slow):
break
return True
slow, val = i, nums[i]
while nums[slow] * val > 0:
tmp = next_index(nums, slow)
nums[slow] = 0
slow = tmp
return False