Java O(n) easy method


  • 0
    P
        public boolean containsDuplicate(int[] nums) {
            Set<Integer> set = new HashSet<Integer>();
            for (int i = 0; i < nums.length; i++) {
                if (set.contains(nums[i]))
                    return true;
                set.add(nums[i]);
            }
            return false;
        }
    

  • 0
    C

    You can eliminate set.contains() call.
    set.add() returns false if the element being added is already present in the set(duplicate).

        public boolean containsDuplicate(int[] nums) {
            HashSet<Integer> set = new HashSet<>();
            for(int i=nums.length-1;i>-1;i--){
                if(!set.add(nums[i])){
                    return true;
                }
            }
            return false;
        }
    

Log in to reply
 

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