Question: https://leetcode.com/problems/contains-duplicate/

Question Name: Contains Duplicate

In general, I found two solutions. The first solution is using hash set:

1 2 3 4 5 6 7 8 | class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ deduplicated = set(nums) return len(deduplicated) != len(nums) |

The second solution is using sorting. We could sort the input and check each pair of adjacent items. Or we could early terminate the sorting if we found two same numbers.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Solution_I(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ nums.sort() for index in xrange(len(nums) - 1): if nums[index] == nums[index + 1]: return True return False ################################################ def compare(num1, num2): if num1 < num2: return -1 elif num1 > num2: return 1 else: raise Exception("Duplicate is found.") return 0 class Solution_II(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ try: nums.sort(cmp = compare) except Exception: return True else: return False |