LeetCode – Contains Duplicate (Java)

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.

Java Solution

public boolean containsDuplicate(int[] nums) {
    if(nums==null || nums.length==0)
        return false;
 
    HashSet<Integer> set = new HashSet<Integer>();
    for(int i: nums){
        if(!set.add(i)){
            return true;
        }
    }
 
    return false;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Charles Gao

    Thank you Vasyl, I found I did not add pre = cur; at the end of the for loop lol

  • Vasyl Grygoryev

    I have similar solution and it works fine. Time complexity is O(n log n) and O(1) extra memory.


    public boolean containsDuplicate(int[] nums) {
    if (nums == null || nums.length < 2)
    return false;

    Arrays.sort(nums);

    for (int i = 1; i < nums.length; i++)
    if (nums[i - 1] == nums[i])
    return true;

    return false;
    }

  • Charles Gao

    Why I only pass 14/16 test cases?? here is my code, thanks in advance

    public class Solution {

    public boolean containsDuplicate(int[] nums) {

    if(nums==null || nums.length==0) return false;

    if(nums.length == 1){

    return false;

    }

    Arrays.sort(nums);

    int pre = nums[0];

    int cur;

    for (int i=1; i<nums.length; i++){

    cur = nums[i];

    if(pre == cur) return true;

    }

    return false;

    }

    }