LeetCode217——存在重复元素
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/contains-duplicate/description/
题目描述:
知识点:哈希表
思路:用一个HashSet来存储已遍历元素
一旦发现重复元素即返回true,如果遍历结束还未发现重复元素,说明数组中不存在重复元素,返回false。
时间复杂度和空间复杂度均是O(n),其中n为数组的长度。
JAVA代码:
public 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;
}else{
set.add(nums[i]);
}
}
return false;
}
}
LeetCode解题报告: