Description:
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and using only constant extra space.
Example 1:
Input: nums = [1,3,4,2,2] Output: 2
Example 2:
Input: nums = [3,1,3,4,2] Output: 3
Example 3:
Input: nums = [3,3,3,3,3] Output: 3
Constraints:
1 <= n <= 105nums.length == n + 11 <= nums[i] <= n- All the integers inÂ
nums appear only once except for precisely one integer which appears two or more times.
Follow up:
- How can we prove that at least one duplicate number must exist inÂ
nums? - Can you solve the problem in linear runtime complexity?
Solution:
class Solution {
public int findDuplicate(int[] nums) {
int len = nums.length;
int[] unique = new int[len];
for(int num:nums){
if(unique[num] == 0){
unique[num] = 1;
}
else{
return num;
}
}
return -1;
}
}
Problem Statement
Given an array
numscontainingn + 1integers where each integer is between1andn(inclusive), exactly one number is repeated. Return the duplicate number.
Approach Explanation
- Create a helper array (
unique) to track seen numbers- Since numbers are between
1andn, we can use an array of sizelen(length ofnums) as a checklist. - Initially, all entries in
uniqueare0.
- Since numbers are between
- Iterate through the
numsarray- For each number
numinnums:- Check
unique[num]:- If it is
0→ this number hasn’t been seen yet → mark it as seen (unique[num] = 1) - If it is
1→ this number has already been seen → return it as the duplicate
- If it is
- Check
- For each number
- Return -1 if no duplicate is found
- This is just a fallback, but the problem guarantees a duplicate exists, so normally this won’t be reached.