217-contains-duplicate
Question
https://leetcode.com/problems/contains-duplicate/description/
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example:
Thought Process
- Sort
- Time complexity O(n logn)
- Space complexity O(1) or O(n) depends on if we can temper the original array
- Hash Table - Set
- Time complexity O(n)
- Space complexity O(n)
Solution
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) return true;
}
return false;
}
}
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums){
if (!set.add(num)) return true;
}
return false;
}
}