leetcode287(寻找重复数)

寻找重复数

给定一个包含 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
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值