Use two loops. In the outer loop, pick elements one by one and count the number of occurrences of the picked element in the inner loop.
This method doesn’t use the other useful data provided in questions like range of numbers is between 1 to n and there are only two repeating elements.
publicclassSolution {
publicbooleancontainsDuplicate(int[] nums) {
int n = nums.length;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i]== nums[j]) {
returntrue;
}
}
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
classSolution:
defcontainsDuplicate(self, nums: List[int]) -> bool:
n = len(nums)
for i in range(n -1):
for j in range(i +1, n):
if nums[i] == nums[j]:
returnTruereturnFalse
publicclassSolution {
publicbooleancontainsDuplicate(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
for (int i = 1; i < n; i++) {
if (nums[i]== nums[i - 1]) {
returntrue;
}
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
classSolution:
defcontains_duplicate(self, nums: List[int]) -> bool:
nums.sort()
n = len(nums)
for i in range(1, n):
if nums[i] == nums[i -1]:
returnTruereturnFalse
publicclassSolution {
publicbooleancontainsDuplicate(int[] nums) {
Set<Integer> seen =new HashSet<>();
for (int num : nums) {
if (seen.contains(num)) {
returntrue;
}
seen.add(num);
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
classSolution:
defcontains_duplicate(self, nums: List[int]) -> bool:
seen = set()
for num in nums:
if num in seen:
returnTrue seen.add(num)
returnFalse
In Java 8, streams can be used to count the distinct elements in an array. If this distinct count differs from the length of the array, it indicates the presence of duplicates.
// Generic function to check for duplicates in an arrayprivatestatic<T>booleancheckForDuplicates(T... array)
{
Long distinctCount = Stream.of(array)
.distinct().count();
return array.length!= distinctCount;
}