217. Contains Duplicate
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.
tips:
1. 两种解法:一种是先排序,再判断有没有重复的(5s 时间复杂度nO(logN),空间复杂度O(1)),另外一种是利用HashSet辅助存储(10s,时间复杂度O(N),空间复杂度O(N))
先排序方式
public class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums==null||nums.length<=0)
return false;
Arrays.sort(nums);
for(int i=1;i<nums.length;i++){
if(nums[i]==nums[i-1])
return true;
}
return false;
}
}
利用HashSet方式:
public class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums==null||nums.length<=0)
return false;
Arrays.sort(nums);
for(int i=1;i<nums.length;i++){
if(nums[i]==nums[i-1])
return true;
}
return false;
}
}