217. Contains Duplicate
Problem Statement
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.
Examples
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
Constraints
nums.length
nums[i]
Submissions
python
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums))
python
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False
Explanations
Python
Submitted by @noeyislearning
class Solution:
: This is the class that contains the functioncontainsDuplicate
.def containsDuplicate(self, nums: List[int]) -> bool:
: This function takes in a list of integersnums
and returns a boolean value.return len(nums) != len(set(nums))
: This line of code checks if the length of the listnums
is not equal to the length of the set ofnums
. If the lengths are not equal, it means that there are duplicates in the list, so the function returnsTrue
. Otherwise, it returnsFalse
.len(nums)
: This returns the length of the listnums
.set(nums)
: This converts the listnums
into a set, which removes duplicates. The length of the set will be less than the length of the list if there are duplicates.
Python
Submitted by @noeyislearning