217. 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.

链接: 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