leetcode 217. Contains Duplicate ( Python )

428 阅读21分钟

描述

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

解析

为了找是否有重复的元素,只要用 set 进行长度比较即可。如果和原数组长度不等那就是 True,否则是 False。时间复杂度为 O(N),空间复杂度为 O(N)。

解答

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
   	 return len(set(nums)) != len(nums)
                   

运行结果

Runtime: 100 ms, faster than 92.90% of Python online submissions for Contains Duplicate.
Memory Usage: 17.1 MB, less than 72.99% of Python online submissions for Contains Duplicate.

每日格言:过去属于死神,未来属于你自己。

感谢支持 支付宝

支付宝

微信

微信