217. Contains Duplicate

本文提供LeetCode题目“含有重复元素”的多种解决方案,包括使用HashSet和Bitmap的方法,并讨论了时间复杂度与空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

链接: http://leetcode.com/problems/contains-duplicate/

题解:

求数组中是否有重复元素。第一反应是用HashSet。 还可以用Bitmap来写。二刷要都补充上。

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        if(nums == null || nums.length == 0)
            return false;
        Set<Integer> set = new HashSet<>();
        
        for(int i : nums) {
            if(set.contains(i))
                return true;
            else
                set.add(i);
        }
        
        return false;
    }
}

 

二刷:

也是跟1刷一样,使用一个Set来判断

Java:

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        Set<Integer> set = new HashSet<>();
        for (int i : nums) {
            if (!set.add(i)) {
                return true;
            }
        }
        return false;
    }
}

 

三刷:

直接使用set的话会超时,我们需要给Set设置一个初始值来避免resizing的过程。一般来说loading factor大约是0.75,最大的test case大约是30000个数字,所以我们用40000左右的容量的HashSet应该就足够了,这里我选的41000。

这道题也可以先排序再比较前后两个元素,那样的话是O(nlogn)时间复杂度,但可以做到O(1)空间复杂度。

Java:

Time Complexity - O(n), Space Complexity - O(1)

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

 

Update:

再写却并没有碰到超时的情况。

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

 

 

Reference:

https://leetcode.com/discuss/70186/88%25-and-99%25-java-solutions-with-custom-hashing

https://leetcode.com/discuss/59208/20ms-c-use-bitmap

https://leetcode.com/discuss/37219/possible-solutions

https://leetcode.com/discuss/37190/java-o-n-ac-solutions-with-hashset-and-bitset

转载于:https://www.cnblogs.com/yrbbest/p/4987090.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值