美文网首页
442. Find All Duplicates in an A

442. Find All Duplicates in an A

作者: 腹黑君 | 来源:发表于2017-08-29 21:02 被阅读0次

    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 A

          本文链接:https://www.haomeiwen.com/subject/zpyadxtx.html