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.
Solution1:hashset
Time Complexity: O(N) Space Complexity: O(N)
Solution2:sort
Time Complexity: O(NlogN) Space Complexity: O(1)
Solution1 Code:
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int num : nums) {
if(set.contains(num)) {
return true;
}
set.add(num);
}
return false;
}
}
Solution2 Code:
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;
}
}