Find All Duplicates in an Array

Given an array of integers, 1 ≤ a[i] ≤n(n= size of array), some elements appeartwiceand others appearonce.

Find all the elements that appeartwicein 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]

分析

有a[i],把index=a[i]-1那个位置的数置为1

class Solution:
    def findDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        ret = []
        n = len(nums)
        if n<=1:
            return ret
        for i in range(n):
            index =  abs(nums[i])-1
            if nums[index]<0:
                ret.append(index+1)
            nums[index] = -nums[index]
        return ret

当前数换到val-1的位置上,所以数是1->n 位置是0->n-1

Last updated

Was this helpful?