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.
解法
利用hashset判断是否重复。
public class Solution {
public boolean containsDuplicate(int[] nums) {
if (nums == null || nums.length == 0) {
return false;
}
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
if (!set.add(nums[i])) {
return true;
}
}
return false;
}
}
本文介绍了一种使用HashSet来检查整数数组中是否存在重复元素的方法。通过遍历数组并将元素添加到HashSet中,若添加失败则表明该元素已存在,从而确定数组中有重复项。
1688

被折叠的 条评论
为什么被折叠?



