There are duplicate elements

Given an array of integers, determine whether there are duplicate elements.

The function returns true if there is a value that appears in the array at least twice. Return false if each element in the array is different.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/co… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: HashSet weight

Use HashSet weight to declare a HashSet variable notRepeatedNums, iterate over nums, and add each digit to notRepeatedNums using add(). If false is returned, the number already exists, that is, duplicate elements exist. Returns true. If true is returned, the current number is added to notRepeatedNums and the next number is iterated. After traversal, return false if there are no repeated digits.

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

public class LeetCode_217 {
    public static boolean containsDuplicate(int[] nums) {
        Set<Integer> notRepeatedNums = new HashSet<>();
        for (int num : nums) {
            if(! notRepeatedNums.add(num)) {return true; }}return false;
    }

    public static void main(String[] args) {
        int[] nums = new int[] {1.2.3.1}; System.out.println(containsDuplicate(nums)); }}Copy the code

A kind man is always happy! Grateful people are always rich! Let us with gratitude and kindness, do not forget the original aspiration, warm forward.