clueless coding // TODO: be smarter

LeetCode 217. Contains Duplicate: Java Solution



Problem Statement


Given an array of integers, design an algorithm to find if it contains duplicates.

Return true if any value appears two or more times in the array.

Return false if every element is distinct.

Function Signature (Java):
  public boolean containsDuplicate(int[] nums)

Inputs:
  nums = [2, 5, 4, 2]

Outputs:
true

Inputs:
  nums = [1, 3, 5, 7]

Outputs:
false



TL;DR Code Solution


public boolean containsDuplicate(int[] nums) {

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

}