217. 存在重复元素

转载自Leet Code

题目描述

给定一个整数数组,判断是否存在重复元素。 如果任意一值在数组中出现至少两次,函数返回true。 如果数组中每个元素都不相同,则返回false

示例 1: >输入: [1,2,3,1] >输出: true

示例 2: >输入: [1,2,3,4] >输出: false

示例 3: >输入: [1,1,1,3,3,4,3,2,4,2] >输出: true

提示:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109

我的代码

\(T(N) = O(N)\), \(S(N) = O(N)\)

{.line-numbers}
1
2
3
4
5
6
7
8
9
10
11
12
13
class MySolution217
{
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;
}
}