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.
数组中如果出现重复的元素返回True,反之
方法一:使用Map复杂度o(n)
public boolean containsDuplicate(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int num:nums)
{
if(!map.containsKey(num))
map.put(num,1);
else
return true;
}
return false;
}
方法二:先排序,再遍历,复杂度o(n)
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int ind = 1; ind < nums.length; ind++) {
if(nums[ind] == nums[ind - 1]) {
return true;
}
}
return false;
}