python(leetcode) - repeated element algorithm

leetcode primary algorithm

Problem description

Given an array of integers, determine whether there are duplicate elements.

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

 

It's very simple to see if there are the same elements in the array

Solution 1: (fail - time limit exceeded)

Idea: use the built-in function count of list to calculate the number of each element. If it is greater than 1, return True. If it is equal to 1, return false

 1 class Solution:
 2     def containsDuplicate(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: bool
 6         """
 7         count=0
 8         if(len(nums)==0):
 9             return False
10         else:
11             for i in nums:
12                 if(nums.count(i)!=1):
13                     return True
14             return False
15 if __name__=="__main__":
16     s=Solution()
17     li=[2,4,6,5]
18     print(s.containsDuplicate(li))

Analysis reason: the built-i n function list.count(i) has a time complexity of O(n) and the total time of nesting a layer of loops outside is O (n^2)

 

Solution 2 (pass)

The idea is to use the built-in function sort() to sort the list first, and then judge whether the two adjacent positions are equal. If they are the same, return True or return False

 1 class Solution:
 2     def containsDuplicate2(self,nums):
 3         nums.sort()
 4         if (len(nums) == 0):
 5             return False
 6         else:
 7             for i in range(len(nums)-1):
 8                 left=nums[i+1]
 9                 right=nums[i]
10                 result=left==right
11                 if(result):
12                     return True
13             return False
14 if __name__=="__main__":
15     s=Solution()
16     li=[2,4,6,5]
17     print(s.containsDuplicate2(li))

Solution 3 (pass)

Idea: make use of the feature of set() that there is no repeating element, and then judge the length of set and list

 1 class Solution:
 2     def containsDuplicate(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: bool
 6         """
 7         set1 = set(nums)
 8         if len(set1) == len(nums):
 9             return False
10         else:
11             return True
12 if __name__=="__main__":
13     s=Solution()
14     li=[2,4,6,5]
15     print(s.containsDuplicate2(li))

Tags: Python

Posted on Wed, 04 Dec 2019 17:13:30 -0500 by lmninfo