leetcode——217. 存在重复元素

leetcode——217. 存在重复元素

题目描述:给定一个整数数组,判断是否存在重复元素。

如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。

示例 1:

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

示例 2:

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

/**
* 思路:将参数中的数组循环遍历,一一添加到一个 HashSet 对象中,HashSet会过滤重复元素,
* 只需要拿数组nums与添加了全部数组元素的set比较,大小不一致则判定数组元素有重复。
* @param nums
* @return
*/
public boolean containsDuplicate(int[] nums) {
        int len = nums.length;
        HashSet<Integer> set = new HashSet<>();
        for(int num : nums) {
            set.add(num);
        }
        int len2 = set.size();
        if(len == len2) {
            return false;
        }
        return true;
}


更新(2021年9月5日)

第二种思路:将参数中的数组循环遍历,一一添加到一个 HashSet 对象中,HashSet添加一个已存在的元素时会返回false,此时程序返回true,否则在循环结束之后返回false。

public boolean containsDuplicate(int[] nums) {
    HashSet<Integer> set = new HashSet<>();
    for(int num : nums) {
        if(!set.add(num)) {
            return true;
        }
    }
    return false;
}

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contains-duplicate
题目著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2021-08-18 22:34  realzhangsan  阅读(34)  评论(0编辑  收藏  举报