Dare2Solve
The problem requires determining if there are any duplicate elements in an array of integers. If any value appears at least twice in the array, return true
. If every element is distinct, return false
.
To find duplicates, sorting the array makes it easier to check if any two consecutive elements are the same. After sorting, any duplicates would be adjacent in the array, allowing for a simple comparison.
Sorting:
Checking for Duplicates:
true
since a duplicate is found.false
.O(n log n)
, where n
is the number of elements in the array. This is due to the sorting step, which dominates the overall time complexity.
class Solution {
public:
bool containsDuplicate(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end());
for (int i = 1; i < nums.size(); i++) {
if (nums[i] == nums[i - 1]) {
return true;
}
}
return false;
}
};
class Solution:
def containsDuplicate(self, nums: list[int]) -> bool:
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return True
return False
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
return true;
}
}
return false;
}
}
/**
* @param {number} n
* @return {number}
*/
var containsDuplicate = function(nums) {
nums.sort((a, b) => a - b);
for (let i = 1; i < nums.length; i++) {
if (nums[i] === nums[i - 1]) {
return true;
}
}
return false;
};