LeetCode287-寻找重复数

题目链接

英文链接:https://leetcode.com/problems/find-the-duplicate-number/

中文链接:https://leetcode-cn.com/problems/find-the-duplicate-number/

题目详述

给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。

示例 1:

1
2
输入: [1,3,4,2,2]
输出: 2

示例 2:

1
2
输入: [3,1,3,4,2]
输出: 3

说明:

  1. 不能更改原数组(假设数组是只读的)。
  2. 只能使用额外的 O(1) 的空间。
  3. 时间复杂度小于 O(n2) 。
  4. 数组中只有一个重复的数字,但它可能不止重复出现一次。

题目详解

  • 对于数组中的每个元素,它有两个参数 indexvalue
  • 通过 index 可以得到 value,而每个 value 都在 1 到 n 之间,故可以通过 nums[value] 得到下一个 index,这样就将数组中的元素串起来了,类似形成了一个链表。
  • 由题意可知,数组中必存在一个重复的数字,则环必然存在。
  • 问题转化为了找链表的环的入口结点 LeetCode142-环形链表II
  • 运用快慢指针的思想解答本题即可, LeetCode142-环形链表II 是链表形式,本题是数组形式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class LeetCode_00287 {

public int findDuplicate(int[] nums) {
int fast = 0;
int slow = 0;
do {
fast = nums[nums[fast]];
slow = nums[slow];
} while (fast != slow);
fast = 0;
while (fast != slow) {
fast = nums[fast];
slow = nums[slow];
}
return fast;
}
}

运用抽屉原理,也可以进行二分查找。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class LeetCode_00287 {

public int findDuplicate(int[] nums) {
int l = 1, r = nums.length - 1;
while (l < r) {
int mid = l + r >>> 1;
int cnt = 0;
for (int num : nums) {
if (num >= l && num <= mid) {
++cnt;
}
}
if (cnt > mid - l + 1) r = mid;
else l = mid + 1;
}
return r;
}
}