217. Contains Duplicate

问题描述

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.

思路

先排序,然后两两对比,有相同的返回True,否则False

    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) ==0: return False
        nums.sort()
        tmp = nums[0]
        for i in range (1, len(nums)):
            if nums[i] == tmp:
                return True
            tmp = nums[i]
        return False
217. Contains Duplicate_第1张图片

别人的骚操作
def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        num_set = set(nums)
        if len(nums) == len(num_set):
            return False
        return True

你可能感兴趣的:(217. Contains Duplicate)