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.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。