题目描述:
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.
思路:
时间复杂度O(N),空间复杂度O(N)
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums)
{
if (set.contains(num))
return true;
else
set.add(num);
}
return false;
}
}
本文介绍了一种使用HashSet数据结构来检查整数数组中是否存在重复元素的方法。该方法的时间复杂度为O(N),空间复杂度也为O(N)。通过遍历数组并将元素添加到HashSet中,若遇到已存在的元素则返回真。
670

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



