───✱*.。:。✱*.:。✧*.。✰*.:。✧*.。:。*.。✱ ───
Problem
Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.
Solution
- Looking at this problem, my naive solution would be to simply do something like
if num in nums: return True.- However, looking up items in array/list is
O(n)time complexity. If we have to do this for every item in the array, we’ll have anO(n^2)time complexity.
- However, looking up items in array/list is
- A better solution would be to use a
set(). Since sets are hashed, checking if an item is in the set isO(1), rather thanO(n).- This simplifies our entire problem into
O(n), rather thanO(n^2). - When creating a set, we sacrifice a small space complexity, though (
O(n)).
- This simplifies our entire problem into
class Solution:
def hasDuplicate(self, nums: List[int]) -> bool:
# time complexity: O(n) * O(1) = O(n)
# space complexity: O(n)
num_map = set()
for num in nums:
if num in num_map:
return True
num_map.add(num)
return False───✱*.。:。✱*.:。✧*.。✰*.:。✧*.。:。*.。✱ ───