算法 Java Leetcode Golang

Find if the array contains any duplicates.

Question

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
See it on Leetcode

1
2
3
For example:
Given: [ 1, 2, 3, 4, 3, 6 ]
It should return true.

Hint

Utilize a dynamic data structure that supports fast search and insert operations.

Solution in Java and Golang

  • java
  • go
1
2
3
4
5
6
7
8
9
10
public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>(nums.length);
for (int x: nums) {
if (set.contains(x)) return true;
set.add(x);
}
return false;
}
}