Contains Duplicate
Determine whether any integer occurs more than once in the array.
Work through the cases
3 examplesInput notation
Space-separated integers on line 1.Expected result
true or false.Case 1
Input
5 2 8 5
Expected output
true
Case 2
Input
1 4 7
Expected output
false
Case 3
Input
-1
Expected output
false
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Comparing every pair works but is slow for large n. Equal values become adjacent after sorting. Sort the array, then check whether any two neighbors are equal.
First, we sort the array nums.
Then, we traverse the array. If there are two adjacent elements that are the same, it means that there are duplicate elements in the array, and we directly return true.
Otherwise, when the traversal ends, we return false.
The time complexity is O(n × log n), where n is the length of the array nums.
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; ++i) {
if (nums[i] == nums[i + 1]) {
return true;
}
}
return false;
}
}Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.
Solutions adapted from Doocs / LeetCode contributors, licensed under CC BY-SA 4.0. Formatting changed; TypeScript versions converted to JavaScript. Supplemental implementations and approach notes added. Adapted solution material is available under the same license.