Contains Duplicate
Problem
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.
Solution
Sorting Solution: O(nlgn) time and O(1) space
public class Solution {
public boolean containsDuplicate(int[] nums) {
if (nums == null || nums.length <= 1) return false;
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) return true;
}
return false;
}
}
Set Solution: O(n) time and O(n) space
public class Solution {
public boolean containsDuplicate(int[] nums) {
if (nums == null || nums.length <= 1) return false;
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) return true;
}
return false;
}
}
One Line Arrays.stream() Solution
public class Solution {
public boolean containsDuplicate(int[] nums) {
return nums.length != Arrays.stream(nums).distinct().count();
}
}
Analysis
This is a trivial problem, but we show three solutions here
Notice that the last Arrays.stream(nums).distinct().count()
compares the length of array