Arrays & Hashing

Contains Duplicate

Estimated reading: 1 minute 31 views

Problem: Duplicate Integer

Given an integer array nums, write a function that returns true if any value appears more than once in the array, otherwise returns false.

Examples:

Example 1:

  • Input: nums = [1, 2, 3, 3]
  • Output: true

Example 2:

  • Input: nums = [1, 2, 3, 4]
  • Output: false
				
					 public boolean hasDuplicate(int[] nums) {
        Set<Integer> uniques = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (uniques.contains(nums[i])) {
                return true;
            }
            uniques.add(nums[i]);
        }
        return false;
    }
				
			
Share this Doc

Contains Duplicate

Or copy link

CONTENTS