Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

LeetCode-Java: 271. Contains Duplicate

Notes May 13 2

Problem Description

Given an integer array nums, return true if any value appears at least twice in the array, and return false if all elements are distinct.

Example 1:

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

Example 2:

Input: nums = [1,2,3,4]
Output: false

Example 3:

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

Solutions

Approach 1: HashSet - Basic Implementation

Time Complexity: O(n), Space Complexity: O(n)

import java.util.HashSet;
import java.util.Set;

class Solution {
    public boolean containsDuplicate(int[] numbers) {
        Set<Integer> collection = new HashSet<>();
        
        for (int value : numbers) {
            if (!collection.contains(value)) {
                collection.add(value);
            } else {
                return true;
            }
        }
        return false;
    }
}

Approach 2: HashSet - Otpimized

The add() method in HashSet returns true when the element is successfully added, and false if the element already exists. This allows for a more concise solution.

import java.util.HashSet;
import java.util.Set;

class Solution {
    public boolean containsDuplicate(int[] numbers) {
        Set<Integer> collection = new HashSet<>();
        
        for (int value : numbers) {
            if (!collection.add(value)) {
                return true;
            }
        }
        return false;
    }
}

HashSet API Reference

The HashSet class implements the Set interface and provides the following commonly used methods:

1. add(E element) - Adds an element to the set. Returns true if the element was added, false if it already exists.

Set<String> fruits = new HashSet<>();
fruits.add("apple");
fruits.add("banana");
fruits.add("apple"); // No effect, "apple" already exists
System.out.println(fruits); // Output: [banana, apple]

2. remove(Object o) - Removes the specified element from the set.

Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.remove(2);
System.out.println(numbers); // Output: [1]

3. contains(Object o) - Checks if the set contains the specified element.

Set<String> fruits = new HashSet<>();
fruits.add("apple");
fruits.add("banana");
System.out.println(fruits.contains("apple"));  // Output: true
System.out.println(fruits.contains("orange")); // Output: false

4. size() - Returns the number of elements in the set.

Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
System.out.println(numbers.size()); // Output: 2

5. isEmpty() - Returns true if the set contains no eelments.

Set<String> fruits = new HashSet<>();
System.out.println(fruits.isEmpty()); // Output: true
fruits.add("apple");
System.out.println(fruits.isEmpty()); // Output: false

6. clear() - Removes all elements from the set.

Set<String> fruits = new HashSet<>();
fruits.add("apple");
fruits.add("banana");
fruits.clear();
System.out.println(fruits); // Output: []

7. iterator() - Returns an iterator over the elements in the set.

Set<String> fruits = new HashSet<>();
fruits.add("apple");
fruits.add("banana");

Iterator<String> iter = fruits.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}
// Output:
// apple
// banana

Iterating with Enhanced For-Loop:

for (String item : fruits) {
    System.out.println(item);
}

Converting to Array:

Set<String> fruits = new HashSet<>();
fruits.add("apple");
fruits.add("banana");

// Convert to array using toArray()
// Passing new String[0] is a common pattern that allows Java to create
// an appropriately sized array based on the collection's size
String[] array = fruits.toArray(new String[0]);

for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
}

8. toArray() - Converts the set to an array of Objects.

Object[] array = fruits.toArray();

Note: HashSet does not maintain insertion order and does not support index-based access since it's implemented using a hash table. The enhanced for-loop or iterator should be used for traversal.

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Spring Boot MyBatis with Two MySQL DataSources Using Druid

Required dependencies application.properties: define two data sources and poooling Java configuration for both data sources MyBatis mappers for each data source Controller endpoints to verify both co...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.