leetcode 287.寻找重复数(find the duplicate number)C语言
1.description
https://leetcode-cn.com/problems/find-the-duplicate-number/description/
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和
n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
示例 1:
输入: [1,3,4,2,2]
输出: 2
示例 2:
输入: [3,1,3,4,2]
输出: 3
说明:
不能更改原数组(假设数组是只读的)。
只能使用额外的 O(1) 的空间。
时间复杂度小于 O(n^2) 。
数组中只有一个重复的数字,但它可能不止重复出现一次。
2.solution
不能更改原数组、只能使用额外的 O(1) 的空间是两个比较苛刻的条件,容易想到的哈希表、排序等办法都被排除,这里参考了大佬的 题解,用到了二分法。本题还有 tricky 的 快慢指针法,更不容易想到。
int findDuplicate(int* nums, int numsSize){
int low = 1, high = numsSize-1;
while(low < high){
int mid = low + (high - low) / 2;
int count = 0;
for(int i=0; i<numsSize; ++i){
if(nums[i]<=mid) count++;
}
if(count > mid){
high = mid;
}else{
low = mid + 1;
}
}
return low;
}