Contains duplicate#
Levels: level-0
Data structures: array, hash-table
Practice Link#
Description#
- Given an array of integers, find if the array contains any duplicates.
- Your function should return
trueif any value appears at least twice in the array, and it should returnfalseif every element is distinct.
Example#
1Input: [1,2,3,1]
2Output: truePython Solution#
1class Solution(object):
2 def containsDuplicate(self, nums):
3 """
4 :type nums: List[int]
5 :rtype: bool
6 """
7 h = {}
8 for n in nums:
9 if n in h:
10 return True
11 h[n] = True
12 return False
13
14
15class Solution2(object):
16 def containsDuplicate(self, nums):
17 """
18 :type nums: List[int]
19 :rtype: bool
20 """
21 return True if len(set(nums)) < len(nums) else False
22
23
24in_arrs = [
25 [2, 1, 2, 1, 0, 1, 2],
26 [3, 3, 5, 0, 0, 3, 1, 4],
27 [3, 5, 0, 1, 4],
28 [1, 2, 3, 1],
29 [1, 2, 3, 4],
30 [1, 1, 1, 3, 3, 4, 3, 2, 4, 2],
31]
32if __name__ == "__main__":
33
34 sol = Solution2()
35 for nin in in_arrs:
36 r = sol.containsDuplicate(nin)
37 print(r)