LeetCode217-duplicate elements exist

topic:

If any value appears at least twice in the array, the function returns true. If each element in the array is different, it returns false.

At first, I think this question is quite simple. The two-layer loop is not ok. However, there is a time limit during the test. OTZ. After reading the comments of a big guy, I feel that I have gained knowledge. I will first paste my ugly. Code

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        flag=0
        if (nums==[] or len(nums)==1 ):
            flag=0
        else:
            for i in range(0,len(nums)):
                for j in range(i+1,len(nums)):
                    if nums[i]==nums[j]:
                        flag=1
                        break
        return bool(flag)


Gangster used the "set" operation, first put on the basic introduction

The set ()  function creates an unordered and non-repetitive element set, which can be used for relationship testing, delete duplicate data, and can also calculate intersections, difference sets, unions, etc.

Just transfer the list to the set type, and just put the answer

class Solution:
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        set1 = set(nums)
        if len(set1) == len(nums):
            return False
        else:
            return True

 

Published 17 original articles · praised 0 · visits 3233

Guess you like

Origin blog.csdn.net/qq_31874075/article/details/88080363