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.
方法1:每个元素都与它后面的元素进行比较,看看有没有重复的
时间复杂度O(N^2)
空间复杂度O(1)
方法2:数组排序,看看相邻的是否有一样的。
时间复杂度O(NlogN)
空间复杂度O(1) (不考虑排序的空间复杂度)
方法3:Set,给一个数,看看Set中有没有一个的,有,则有重复了,没有,放入Set。
时间复杂度O(N)
空间复杂度O(N)
运行时间:
代码:
public boolean containsDuplicate(int[] nums) {
Set<Integer> sets = new HashSet<>();
for (int num : nums) {
if (!sets.add(num)) {
return true;
}
}
return false;
}
直接放入set,如果有重复,add函数会返回false。
如果先判断contains,相当于增加了额外的判断contains步骤,速度会变慢。