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.
给定一个数组,观察是否包含重复的元素。
算法分析
方法一:
将数组中的元素以此存入set中
Java代码
public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> numsSet = new HashSet<>();
for (int i = 0; i < nums.length; i ++) {
if (numsSet.contains(nums[i])) return true;
else numsSet.add(nums[i]);
}
return false;
}
}
方法二:
先将数组排序,然后比较前否两个元素是否相同。
public 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;
}
}