[leetcode] 287.Find the Duplicate Number

题目:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate element must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:
You must not modify the array (assume the array is read only).
You must use only constant extra space.
Your runtime complexity should be less than O(n2).
题意:
给定一个含有n+1个元素的整数数组,包含的元素的大小是1到n。证明最少有一个元素重复了。假设只有一个重复元素,找出这个重复元素。
思路:
因为这个数组的特点非常明显,元素的大小是在1到n之间,而且只有一个元素是重复出现的。那么如果我们存储nums[i] = i + 1,那么对于重复的那个元素j,两个元素都想存放在nums[j-1]中。所以我们可以将元素放入它应该放的位置,比如k应该放在数组的下标k-1的位置。我们遍历数组,将扫描到的数字k放到它应该放的位置k-1,可以将当前元素与nums[k-1]交换,继续将当前位置上交换得到的值放到它应该出现的位置。循环的终止条件是当前位置存放的值就是应该存放的数字,或者当前位置想把数字k交换到它的指定位置时,发现那个位置已经存放了一个k,如果是遇到这个终止条件,那么将需要返回这个值k。
以上所述。
代码如下:

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        if(nums.empty())return -1;
        for(int i = 0; i < nums.size(); i++) {
            while(nums[i] != i + 1 && nums[nums[i] - 1] != nums[i])swap(nums[nums[i] - 1], nums[i]);
            if(nums[i] != i + 1)return nums[i];
        }
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值