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.
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Input: nums = [3,1,4,2]
Output: false
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To solve this problem in linear time complexity (O(n)), you can use the following algorithm:
duplicates
.x
in the array: a. Ifx
is induplicates
, returntrue
. b. Otherwise, addx
toduplicates
.false
.Here is some example code in Python that implements this algorithm:
def containsDuplicate(nums):
duplicates = set()
for x in nums:
if x in duplicates:
return True
duplicates.add(x)
return False
This algorithm has a time complexity of O(n), as it requires iterating through the array once and performing a constant number of operations for each element.
I hope this helps! Let me know if you have any questions.