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 number 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, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.

给定一个长度为n + 1的数组nums[],里面的元素nums[i]都在1到n之间,只有一个重复元素,让我们找到这个元素,空间复杂度为O(1),时间复杂度不多于O(n^2)。我们可以将数组排序,然后通过二分法找到重复的元素,排序之后,如果中间的元素的值小于或等于中间元素的下标,即nums[m] <= m, 说明重复的元素肯定在m的左边(因为元素的值是从1开始,如果左边没有重复元素,所以中间元素的值肯定会大于中间元素的下标。),让右指针变为m - 1; 否则让左指针变为m+1。这样时间复杂度为O(nlogn)。代码如下:

public class Solution {
public int findDuplicate(int[] nums) {
Arrays.sort(nums);
int l = 0;
int r = nums.length - 1;
while(l < r) {
int m = l + (r - l) / 2;
if(nums[m] <= m) {
r = m - 1;
} else {
l = m + 1;
}
}
return nums[l];
}
}


还有一个很巧妙的方法,只需要O(n)的时间复杂度。我们从第一个元素开始,如果nums[nums[i]]大于0,就把nums[nums[i]]设定为负数,因为只有一个元素重复,当我们往后处理,遇到nums[nums[i]]小于0,说明我们之前访问过这个元素,因此当前元素的值为重复的元素。代码如下:

public class Solution {
public int findDuplicate(int[] nums) {
int result = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[Math.abs(nums[i])] > 0) {
nums[Math.abs(nums[i])] = - nums[Math.abs(nums[i])];
} else {
result = Math.abs(nums[i]);
}
}
return result;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值