给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
首先想到的解法是最简单的循环,这样做的时间复杂度是O(
n
2
n^2
n2),但事实最容易想到的方法:
class Solution {
public boolean containsDuplicate(int[] nums) {
for(int i = 0;i < nums.length-1;i++){
for(int j =i+1;j < nums.length;j++){
if(nums[i] == nums[j]){
return true;
}
}
}
return false;
}
}
方法一:排序
先将数组进行排序,再遍历0-len-1,与他的下一个进行判等,时间复杂度为O(
n
l
o
g
n
nlogn
nlogn):
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums); //排序为快速排序
for(int i = 0;i < nums.length-1;i++){
if(nums[i] == nums[i+1]){
return true;
}
}
return false;
}
}
方法二:哈希,时间复杂度为O( n n n)
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> hash = new HashSet<Integer>();
for(int i = 0;i < nums.length;i++){
if(!hash.add(nums[i])){
return true;
}
}
return false;
}
}