[关闭]
@xlsd1996 2018-03-11T07:05:21.000000Z 字数 808 阅读 715

Leetcode 解题思路

leetcode 第442题

题目链接:Find All Duplicates in an Array


题目描述:给一个包含 n 个数的数组 a,其中有的出现两次,有的出现一次,而且所有的数都满足 1 <= a[i] <= n,目标:找出所有出现重复的数,要求:不使用额外空间,时间复杂度 O(n)

乍一看感觉需要先排序,然后遍历,然后想到 计数排序 这类排序方法的思想:把对应元素放到对应位置上


于是有一个解决方法:

  1. 一个指针指向起始位置
  2. 若这个指针指向的数字与其索引不相符合 且 这个数字不是 -1 时,尝试 将这个数字与这个数字对应的索引地址上的数交换,否则指针向前
  3. 若待交换时两个数相同,则说明出现了重复的数,交换失败,此时记录下这个数,在此时指针处标记 -1 ,指针继续向前
  4. 若交换成功,则指针不移动,重复 步骤1
  5. 若指针到达数组尾部,结束

流程图如下

Created with Raphaël 2.1.2i=0,res=[ ]nums[i]-1 == i && nums[i] != -1判断是否重复:nums[ nums[i]-1 ] ==nums[i]出现重复数字,将nums[ nums[i]-1 ]保存在res中,nums[i]=-1i += 1i > len(nums)返回resyesnoyesyesno

Python代码如下:

  1. class Solution(object):
  2. def findDuplicates(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: List[int]
  6. """
  7. i=0
  8. res = []
  9. while(i<len(nums)):
  10. if(nums[i]!=-1 and nums[i] != i+1):
  11. temp = nums[nums[i]-1]
  12. if(nums[i]==temp):
  13. res.append(temp)
  14. nums[i]=-1
  15. else:
  16. nums[nums[i]-1] = nums[i]
  17. nums[i] = temp
  18. continue
  19. i += 1
  20. return res
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注