442. 数组中重复的数据
满足要求的元素是 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
面试题 17.19. 消失的两个数字
class Solution(object):
def missingTwo(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums.append(-1)
nums.append(-1)
for i in range(len(nums)):
while nums[nums[i]-1] != nums[i] and nums[i]!= -1:
k = nums[i] - 1
nums[i],nums[k] = nums[k],nums[i]
res = []
for i in range(len(nums)):
if nums[i] == -1:
res.append(i+1)
return res