【LeetCode】217. Contains Duplicate 存在重复元素(Easy)(JAVA)
题目地址: https://leetcode.com/problems/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.
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
题目大意
给定一个整数数组,判断是否存在重复元素。
如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
解题方法
- 用一个 HashSet 来存,先判断是否在 set 里面有,如果有就说明有重复的
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;
}
}
执行耗时:8 ms,击败了54.98% 的Java用户
内存消耗:44.4 MB,击败了46.36% 的Java用户