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?
思路:Just think it as finding a loop in Linkedlist, except that loops with only 1 element do not count. Use a slow and fast pointer, slow pointer moves 1 step a time while fast pointer moves 2 steps a time. If there is a loop (fast == slow), we return true, else if we meet element with different directions, then the search fail, we set all elements along the way to 0. Because 0 is fail for sure so when later search meet 0 we know the search will fail.
class Solution(object):
def circularArrayLoop(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n = len(nums)
def getIndex(i):
return (i+nums[i])%n
for i in range(n):
if not nums[i]: continue
#slow/faster pointer
j, k = i, getIndex(i)
while(nums[k]*nums[i]>0 and nums[getIndex(k)]*nums[i]>0): # check fast pointer is enough
if j == k:
# check the loop has more than 1 element
if j == getIndex(j): break
return True
j = getIndex(j)
k = getIndex(getIndex(k))
# if not return from while, set all elements along the way to 0
j = i
while nums[j]*nums[i]>0:
nums[j] = 0
j = getIndex(j)
return False
s=Solution()
print(s.circularArrayLoop([2, -1, 1, 2, 2]))
print(s.circularArrayLoop([-1, 2]))