442. 数组中重复的数据
?原地Hash - SegmentFault 思否
满足要求的元素是 nums[i] (当前遍历到的元素),放到对应的下标:nums[i]-1 (注意这个是下标)
所以是 nums[nums[i]-1] = nums[i] ,把nums[i]放到下标nums[i]-1上。
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(len(nums)):
while nums[nums[i]-1] != nums[i]:
#用一个中间变量保存
k = nums[i]-1
nums[i],nums[k] = nums[k],nums[i]
# nums[k],nums[i] = nums[i],nums[k]
# nums[nums[i]-1],nums[i] = nums[i],nums[nums[i]-1]
# nums[i],nums[nums[i]-1] = nums[nums[i]-1],nums[i]
res= []
for i in range(len(nums)):
if nums[i] != i+1:
res.append(nums[i])
return res
|