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.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
难度:easy
题目:给定整数数组,找出其中是否含有重复元素。方法应该返回true如果发现某元素至少出现两次,否则返回false.
思路:hashset
Runtime: 10 ms, faster than 64.18% of Java online submissions for Contains Duplicate.
Memory Usage: 40.9 MB, less than 81.42% of Java online submissions for Contains Duplicate.
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (set.contains(nums[i])) {
return true;
}
set.add(nums[i]);
}
return false;
}
}