您的位置:首页 > 其它

[leetcode] 287.Find the Duplicate Number

2015-09-28 13:25 169 查看
题目:

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];
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: