217. Contains Duplicate *

来源:互联网 发布:淘宝怎么判定定制产品 编辑:程序博客网 时间:2024/05/18 22:44

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.

My code:

class Solution(object):    def containsDuplicate(self, nums):        """        :type nums: List[int]        :rtype: bool        """        n = len(nums)        if len(nums)<2:           return False        nums.sort()        for i in range(1,n):            if nums[i]== nums[i-1]:                return True        return False

If the dictionary is used to find the duplicates, there would be a lot of searching about the keys. So the list should be sorted first to save time.

0 0
原创粉丝点击