forked from shijbian/LeetCode
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircular-array-loop.py
More file actions
Latest commit
51 lines (45 loc) · 1.79 KB
/
Copy pathcircular-array-loop.py
File metadata and controls
51 lines (45 loc) · 1.79 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Time: O(n)
# Space: O(1)
# 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?
classSolution(object):
defcircularArrayLoop(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
defnext_index(nums, i):
return (i+nums[i]) %len(nums)
foriinxrange(len(nums)):
ifnums[i] ==0:
continue
slow, fast=i, i
whilenums[next_index(nums, slow)] *nums[i] >0and \
nums[next_index(nums, fast)] *nums[i] >0and \
nums[next_index(nums, next_index(nums, fast))] *nums[i] >0:
slow=next_index(nums, slow)
fast=next_index(nums, next_index(nums, fast))
ifslow==fast:
ifslow==next_index(nums, slow):
break
returnTrue
slow, val=i, nums[i]
whilenums[slow] *val>0:
tmp=next_index(nums, slow)
nums[slow] =0
slow=tmp
returnFalse