Simple Java Solution Using HashSet O(n)


  • 8
    F
    public class Solution {
        public boolean containsDuplicate(int[] nums) {
            Set<Integer> set = new HashSet<>();
            for(int i : nums){ set.add(i); }
            return nums.length!=0 && set.size()!=nums.length;
        }
    }

  • 0
    J

    Hey, the solution is nice.I have a small improvement on the above

    public class Solution {
        public boolean containsDuplicate(int[] nums) {
         boolean flag=true;
         Set<Integer> numList=new HashSet<Integer>();
         for(int i=0;i<nums.length&&flag;i++){
            flag = numList.add(nums[i]);
         }
         return !flag;
        }
    }
    

    The add function returns a boolean as to whether there are duplicates or not.If duplicate is present, then false is returned from add.As a result we needn't have to traverse the entire array to find whether duplicates exist


  • 0
    P

    When you have found an element exist in the set, it is okay to return from the function and no need to go on.


Log in to reply
 

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