方法一:排序法
利用Arrays类的中的sort方法进行快速排序,再遍历数组,对数组进行比较。得出结果
class Solution
{
public boolean containsDuplicate(int[] nums)
{
Arrays.sort(nums);
int n = nums.length;
for(int i = 1;i < n;i++)
{
if(nums[i] == nums[i-1])
{
return true;
}
}
return false;
}
}
方法二:哈希表法
class Solution
{
public boolean containsDuplicate(int[] nums)
{
Set<Integer> set = new HashSet<Integer>();
for (int a : nums)
{
if (!set.add(a))
{
return true;
}
}
return false;
}
}