Problem : https://leetcode.com/problems/contains-duplicate
Use hash table to find the duplicate. Time complexity = O ( N )
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
counter = Counter(nums)
return any( counter[n] >= 2 for n in nums )
Sort the input array first, then find the duplicate. Time complexity = O ( N * Log N )
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
nums.sort()
return any(nums[i-1] == nums[i] for i in range(1, len(nums)))
Edited on 05/02/2021. Update hash table approach.
Edited on 05/02/2021. Update locating if sorted array approach.
No comments:
Post a Comment