Skip to content

Commit 0c59028

Browse files
authored
Add 457_Circular_Array_Loop.py (qiyuangong#34)
* Add 457_Circular_Array_Loop.py, by @yuchenliu15
1 parent e0168c2 commit 0c59028

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

python/457_Circular_Array_Loop.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def circularArrayLoop(self, nums: List[int]) -> bool:
3+
for i in range(len(nums)):
4+
if nums[i] == 0:
5+
continue
6+
7+
# if slow and fast pointers collide, then there exists a loop
8+
slow = i
9+
fast = self.index(nums, slow)
10+
while nums[slow] * nums[fast] > 0 and nums[slow] * nums[self.index(nums, fast)] > 0:
11+
if slow == fast and fast != self.index(nums, fast):
12+
return True
13+
elif slow == fast and fast == self.index(nums, fast):
14+
break
15+
slow = self.index(nums, slow)
16+
fast = self.index(nums, self.index(nums, fast))
17+
18+
# set path to all 0s since it doesn't work
19+
runner = i
20+
value = nums[runner]
21+
while nums[runner] * value > 0:
22+
temp = self.index(nums, runner)
23+
nums[runner] = 0
24+
runner = temp
25+
return False
26+
27+
def index(self, nums, index):
28+
length = len(nums)
29+
return (index + nums[index] + length) % length

0 commit comments

Comments
 (0)