寻找重复数
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
示例 1:
输入: [1,3,4,2,2]
输出: 2
示例 2:
输入: [3,1,3,4,2]
输出: 3
说明:
不能更改原数组(假设数组是只读的)。
只能使用额外的 O(1) 的空间。
时间复杂度小于 O(n2) 。
数组中只有一个重复的数字,但它可能不止重复出现一次。
*/C++解法
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int left = 0, right = nums.size()-1;
while(left <= right){
int mid = (left + right)/2, cnt = 0;
for(int num : nums) {
if(num <= mid) ++cnt;
}
if(cnt <= mid) left = mid + 1;
else right = mid - 1;
}
return left;
}
};
*/
class Solution{
public:
int findDuplicate(vector<int>& nums) {
int slow = 0, fast = 0, t = 0;
while(true) {
slow = nums[slow];
fast = nums[nums[fast]];
if(slow == fast) break;
}
while(true){
slow = nums[slow];
t = nums[t];
if (slow == t) break;
}
return slow;
}
};
*/
class Solution{
public:
int findDuplicate(vector<int>& nums){
int res = 0, n = nums.size();
for(int i = 0; i < 32 ;++i){
int bit =(1 << i), cnt1 = 0, cnt2 = 0;
for(int k = 0; k<n; k++){
if((k & bit) > 0) ++cnt1;
if ((nums[k] & bit) >0) ++cnt2;
}
if (cnt2 > cnt1) res += bit;
}
return res;
}
};
*/Python 解法
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
left = 0
right = len(nums)-1
while(left <= right):
mid = (left+right)//2
count = 0
for i in range(len(nums)):
if nums[i] <= mid:
count+=1
if count > mid:
right = mid -1
else:
left = mid +1
return left
*/
class Solution:
def findDuplicate(self,nums):
slow = nums[0]
fast = nums[nums[0]]
while(slow != fast):
slow = nums[slow]
fast = nums[nums[fast]]
fast = 0
while(fast != slow):
slow = nums[slow]
fast = nums[fast]
return slow