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.
Input: [1, 2, 3, 1]
Output: true
Input: [1, 2, 3, 4]
Output: false
Input: [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
Output: true
/**
* Time complexity : O(N^2)
* Space complexity : O(1)
*/
class Solution {
public boolean containsDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if (nums[j] == nums[i]) return true;
}
}
return false;
}
}
/**
* Time complexity : O(NlogN)
* Space complexity : O(1)
*/
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int i = 1; i < nums.length; i++) {
if(nums[i-1] == nums[i]) {
return true;
}
}
return false;
}
}
/**
* Time complexity : O(N)
* Space complexity : O(N)
*/
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> numsSet = new HashSet();
for(int num: nums) {
if(!numsSet.add(num)) {
return true;
}
}
return false;
}
}