Sorting
Intuition
If we sort the array, any duplicate elements will become adjacent to each other. We can then make a single pass through the sorted array and check if any two consecutive elements are equal. This avoids the need for extra data structures but modifies the input array and has O(n log n) time due to sorting. It is a good approach when space is a concern.
Algorithm
- Sort the array in non-decreasing order.
- Iterate through the sorted array from index 1 to n-1.
- At each index i, compare nums[i] with nums[i-1].
- If they are equal, a duplicate exists -- return true.
- If the loop completes without finding any adjacent duplicates, return false.
O(n log n)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
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 {
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;
}
}def containsDuplicate(nums: list[int]) -> bool:
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return True
return Falseimport "sort"
func containsDuplicate(nums []int) bool {
sort.Ints(nums)
for i := 1; i < len(nums); i++ {
if nums[i] == nums[i-1] {
return true
}
}
return false
}