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;
}

4 thoughts on “LeetCode – Contains Duplicate (Java)”


  1. public boolean containsDuplicate(int[] x){
    List list=Arrays.stream(x).boxed().collect(Collectors.toList());
    for(int i=0;i<x.length;i++){
    if(Collections.frequency(list, i)==2)
    return true;
    }
    return false;
    }

  2. 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;
    }

  3. 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;

    }

    }

Leave a Comment