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

#442. Find All Duplicates in an

作者: Double_E | 来源:发表于2017-05-02 20:48 被阅读50次

    https://leetcode.com/problems/find-all-duplicates-in-an-array/#/description

    image.png

    Python (超时了)

    class Solution(object):
        def findDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            d = dict()
            for num in nums:
                if num not in d.keys():
                    d[num] = 1
                else:
                    d[num] += 1
            return [k for k, v in d.items() if v == 2]
    

    Python

    • 不要用key in dict.keys() 很慢
    • 用dict.has_key(key)很快
    class Solution(object):
        def findDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            d = dict()
            re = []
            for num in nums:
                if not d.has_key(num):
                    d[num] = 1
                else:
                    d[num] += 1
                    re.append(num)
            return re
    

    相关文章

      网友评论

          本文标题:#442. Find All Duplicates in an

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