|
| 1 | +# Given an integer array nums, return true if any value appears more than once in the array, otherwise return false. |
| 2 | +# Example: |
| 3 | +# Input: nums = [1, 2, 3, 3] |
| 4 | +# Output: true |
| 5 | + |
| 6 | +# method 1: using hashset |
| 7 | +def hasDuplicate(nums): |
| 8 | + hashset = set() |
| 9 | + |
| 10 | + for i in nums: |
| 11 | + if i in hashset: |
| 12 | + return True |
| 13 | + hashset.add(i) |
| 14 | + return False |
| 15 | + |
| 16 | +print(hasDuplicate([1,2,3,4])) # False |
| 17 | +print(hasDuplicate([1,1,1,3,3,4,3,2,4,2])) # True |
| 18 | +print(hasDuplicate([1,2,3,1])) # True |
| 19 | + |
| 20 | +# method 2: using hashmap |
| 21 | +def check_duplicate(nums): |
| 22 | + seen = {} |
| 23 | + for i in nums: |
| 24 | + if i not in seen: |
| 25 | + seen[i] = 1 |
| 26 | + else: |
| 27 | + seen[i] += 1 |
| 28 | + |
| 29 | + for j in seen: |
| 30 | + if seen[j] > 1: |
| 31 | + return True |
| 32 | + return False |
| 33 | + |
| 34 | +print(check_duplicate([1, 2, 3, 3])) |
| 35 | +print(check_duplicate([1, 2, 3, 4])) |
| 36 | +print(check_duplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])) |
| 37 | +print(check_duplicate([1, 2, 3, 1])) |
| 38 | + |
| 39 | + |
0 commit comments