0
点赞
收藏
分享

微信扫一扫

LeetCode 217.存在重复元素(简单)

LeetCode 217.存在重复元素(简单)_遍历数组

题目描述

LeetCode 217.存在重复元素(简单)_数组_02


给你一个整数数组 ​​nums​​ 。如果任一值在数组中出现 至少两次 ,返回 ​​true​​​ ;如果数组中每个元素互不相同,返回 ​​false​​ 。

LeetCode 217.存在重复元素(简单)_遍历数组

示例 1

LeetCode 217.存在重复元素(简单)_数组_02


输入:nums = [1,2,3,1]
输出:true

LeetCode 217.存在重复元素(简单)_遍历数组

示例 2

LeetCode 217.存在重复元素(简单)_数组_02


输入:nums = [1,2,3,4]
输出:false

LeetCode 217.存在重复元素(简单)_遍历数组

示例 3

LeetCode 217.存在重复元素(简单)_数组_02


输入:nums = [1,1,1,3,3,4,3,2,4,2]
输出:true

LeetCode 217.存在重复元素(简单)_遍历数组

提示

LeetCode 217.存在重复元素(简单)_数组_02


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

LeetCode 217.存在重复元素(简单)_遍历数组

题目分析

LeetCode 217.存在重复元素(简单)_数组_02


这道题很简单,直接使用哈希集合解决就行。遍历数组中的每个元素,检查集合中是否存在相同的元素,存在即返回 ​​true​​​ ,不存在则把新元素添加进集合,最后遍历完没有存在相同的元素就直接返回 ​​false​​ 即可。

LeetCode 217.存在重复元素(简单)_遍历数组

题解

LeetCode 217.存在重复元素(简单)_数组_02


执行用时: 7 ms

内存消耗: 54.1 MB

class Solution {
public boolean containsDuplicate(int[] nums) {
// 创建一个哈希集合
HashSet<Integer> integers = new HashSet<>();
// 遍历数组中的元素
for (int x : nums) {
// 如果集合中存在数组中的元素
if (integers.contains(x)) {
// 证明存在重复元素
return true;
}
// 否则添加新元素到集合中
integers.add(x);
}
// 没有存在重复元素
return false;
}
}

题目来源:力扣(LeetCode)




举报

相关推荐

0 条评论