Skip to main content

0217 Contains Duplicate

Solved at: 2023-01-29

Questionโ€‹

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.

Solutionโ€‹

class Solution {
func containsDuplicate(_ nums: [Int]) -> Bool {
var set = Set<Int>()
for num in nums {
if set.contains(num) {
return true
}
else {
set.insert(num)
}
}
return false
}
}

Resultsโ€‹

  • Runtime 642 ms Beats 44.57%
  • Memory 19 MB Beats 10.85%

Complexity Analysisโ€‹

Both O(N)O(N)

Takeawaysโ€‹

Using sorting can sacrifice time to O(NlogโกN)O(N \log N) and pull down space into O(1)O(1)