Link: https://leetcode.com/problems/contains-duplicate/
Similar question on neetcode: https://neetcode.io/problems/duplicate-integer/
Given an integer array nums
, return true
if any value appears at least twice in the array, and return false if every element is distinct.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
This question is defintely faster to use set()
to check for duplicate, and use the len to compare.
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return (len(nums) != len(set(nums)))
This method will timeout for large list
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n = 0
for i in nums:
if i in nums[n+1:]:
return True
n += 1
return False