442. Find All Duplicates in an Array
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?
给一个数组,数组元素大于等于1小于等于n,有的元素出现了1次有的2次,问出现2次的都是哪些?
元素都是正数,并且在1-n里,那么可以nums[abs(value) - 1] -= nums[abs(value) - 1],在遇到nums[abs(value) - 1]<0的时候就说明这个value出现了2次
class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ ans = [] for value in nums: value = abs(value) if nums[value - 1] < 0: ans.append(value) nums[value - 1] = -nums[value - 1] return ans