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.

[4,3,2,7,8,2,3,1]

Output:
[2,3]

首先是笨方法,超时

    def findDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res = []
        for i in nums:
            num = nums.count(i)
            if num > 1 and i not in res:
                res.append(i)
        return res

网上看的解法,其实就是用-1去标记已出现过的元素

    def findDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res = []
        for i in nums:
            if nums[abs(i)-1]<0:
                res.append(abs(i))
            else:
                nums[abs(i)-1] *= -1
        return res

你可能感兴趣的:(442. Find All Duplicates in an Array)