2
头图

There are duplicate elements

Title description: Given an integer array, determine whether there are duplicate elements.

If there is a value that appears at least twice in the array, the function returns true. If each element in the array is different, false is returned.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/contains-duplicate/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: HashSet judges heavy
Use HashSet to judge heavy, declare a HashSet variable notRepeatedNums, traverse the array nums, add each digit to add() method 0614c78983f7e3, if it returns false, it means that the number already exists, that is, there are duplicate elements, return true; if it returns If true, the current number will be added to notRepeatedNums, and then the next number will be traversed. After the traversal is complete, if there are no repeated numbers, return false.
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));
    }
}
[Daily Message] Kind people are always happy! People who are grateful are always rich! Let us move forward with gratitude and kindness, not forgetting our original intention, and warmth.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!