原题网址: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.
方法:哈希集合。
public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int num: nums) {
if (!set.add(num)) return true;
}
return false;
}
}

本文介绍了一种使用哈希集合解决LeetCode上含有重复元素问题的方法。通过将数组中的每个元素加入到哈希集合中,如果发现某个元素已经存在于集合内,则说明存在重复元素。
1721

被折叠的 条评论
为什么被折叠?



