LeetCode刷题实战217:存在重复元素
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
题意
示例
示例 1:
输入: [1,2,3,1]
输出: true
示例 2:
输入: [1,2,3,4]
输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
解题
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> hashSet = new HashSet<>();
if (nums.length <= 1) return false;
for (int num : nums) {
if (hashSet.contains(num)) return true;
else hashSet.add(num);
}
return false;
}
}
评论