Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
Subscribe to see which companies asked this question.
主要就是不用额外的空间 以及O(n)。
所以就用数组内部数值进行标记,每次访问,把数值对应的index对应的数标记为负数,要是第二次遇见负数,那就说明出现两次了
class Solution(object):
def findDuplicates(self, nums):
res = []
for i in xrange(len(nums)):
idx = abs(nums[i]) - 1
if nums[idx] < 0:
res += idx+1,
nums[idx] = -abs(nums[idx])
#print idx,nums,res
return res

本文介绍了一种在不使用额外空间的情况下找出数组中所有重复元素的方法,该方法的时间复杂度为O(n)。通过将数组中的数值作为索引来标记其对应位置的元素,若遇到已标记的元素则表明该元素为重复项。
353

被折叠的 条评论
为什么被折叠?



