Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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 uses 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
Constraints:
1 <= n <= 105
nums.length == n + 1
1 <= nums[i] <= n
nums
appear only once except for precisely one integer which appears two or more times.Follow up:
nums
? public static int findDuplicate_2loops(int[] nums) {
int len = nums.length;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (nums[i] == nums[j]) {
return nums[i];
}
}
}
return len;
}
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int low = 1, high = nums.size() - 1, cnt;
while(low <= high)
{
int mid = low + (high - low) / 2;
cnt = 0;
// cnt number less than equal to mid
for(int n : nums)
{
if(n <= mid)
++cnt;
}
// binary search on left
if(cnt <= mid)
low = mid + 1;
else
// binary search on right
high = mid - 1;
}
return low;
}
};
class Solution:
def findDuplicate(self, nums):
slow, fast = nums[0], nums[0]
while True:
slow, fast = nums[slow], nums[nums[fast]]
if slow == fast: break
slow = nums[0];
while slow != fast:
slow, fast = nums[slow], nums[fast]
return slow
In our experience, we suggest you solve this Find the Duplicate Number LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Find the Duplicate Number LeetCode Solution
I hope this Find the Duplicate Number LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>