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.
方法一(超时)
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;
}
}
方法二
先排序再比较
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;
}
}
方法三
利用hashset的去重特性
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<Integer>();
for(int i=0;i<nums.length;i++){
set.add(nums[i]);
}
return set.size()!=nums.length;
}
}