Java solution using 5ms


  • 0
    W
    public class Solution {
        public boolean containsDuplicate(int[] nums) {
            if (nums.length <= 1) {
                return false;
            }
            Arrays.sort(nums);
            for (int i = 0; i < nums.length - 1; i++) {
                if (nums[i] == nums[i+1]) {
                    return true;
                }
            }
            return false;
        }
    }
    

  • 0
    R

    Time complexity is O(nlogn)
    you can do this in O(n)


  • 0
    W

    @reemak hello, is the O(n) solution use hashtable?


  • 0
    R

    @whspecial I used a Hashset. Better than a HashMap

    This is my solution:

    public boolean containsDuplicate(int[] a) {
    HashSet<Integer> set=new HashSet<Integer>();
    if(a.length==0 || a.length==1)
    {
    return false;
    }
    else
    {
    for(int i=0;i<a.length;i++)
    {
    if(set.contains(a[i]))
    return true;
    else
    set.add(a[i]);
    }
    }
    return false;

    }
    

    Its always better to have good time complexity over space complexity


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.