这类题一般有个前提:
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array)
442. Find All Duplicates in an Array
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n=len(nums)
for i in range(len(nums)):
nums[(nums[i]-1)%n]+=n
ret=[]
for i in range(n):
if nums[i]>2*n:#should be '>', not '>='
ret.append(i+1)
return ret
optimize version
res=[]
for num in nums:
index=abs(num)-1
if nums[index]<0:
res.append(abs(index)+1)
nums[index]=-nums[index]
return res
287. Find the Duplicate Number
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)<=1:
return -1
fast=nums[nums[0]]
slow=nums[0]
while slow!=fast:
fast=nums[nums[fast]]
slow=nums[slow]
if slow == fast:
break
fast=0
while True:
slow=nums[slow]
fast=nums[fast]
if slow==fast:
return slow
565. Array Nesting
class Solution(object):
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
visited=[0 for i in range(len(nums))]
ret=0
for i in range(len(nums)):
cnt=0
j=i
while not visited[j]:
visited[j]=1
cnt+=1
j=nums[j]
ret=max(cnt,ret)
return ret