题目描述:
LeetCode 457. Circular Array Loop
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.
Example 3: Given the array [2, 0, 2, 1, 3], return false since 0 is not supposed to appear in the array.
Can you do it in O(n) time complexity and O(1) space complexity?
题目大意:
给定一个整数数组。如果某下标位置的数字n为正数,则向前移动n步。反之,如果是负数,则向后移动-n步。假设数组首尾相接。判断数组中是否存在环。环中至少包含2个元素。环中的元素一律“向前”或者一律“向后”。
满足O(n)时间复杂度和O(1)空间复杂度。
解题思路:
三次遍历数组:
第一次遍历,将所有指向自己的元素置0 第二次遍历,从0到n(循环一周),将指向非负数的负数置0 第三次遍历,从n到0(循环一周),将指向非正数的正数置0
遍历结束后,如果数组中存在非零元素,则返回True;否则返回False
Python代码:
class Solution(object):
def circularArrayLoop(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or not all(nums): return False
size = len(nums)
next = lambda x : (x + size + nums[x]) % size
for x in range(size):
if next(x) == x:
nums[x] = 0
for x in range(size + 1):
x = x % size
if nums[x] < 0 and nums[next(x)] >= 0:
nums[x] = 0
for x in range(size, -1, -1):
x = x % size
if nums[x] > 0 and nums[next(x)] <= 0:
nums[x] = 0
return any(nums)