-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0287.寻找重复数.java
78 lines (75 loc) · 1.54 KB
/
0287.寻找重复数.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* @lc app=leetcode.cn id=287 lang=java
*
* [287] 寻找重复数
*
* https://leetcode.cn/problems/find-the-duplicate-number/description/
*
* algorithms
* Medium (64.83%)
* Likes: 1794
* Dislikes: 0
* Total Accepted: 250.5K
* Total Submissions: 386.5K
* Testcase Example: '[1,3,4,2,2]'
*
* 给定一个包含 n + 1 个整数的数组 nums ,其数字都在 [1, n] 范围内(包括 1 和 n),可知至少存在一个重复的整数。
*
* 假设 nums 只有 一个重复的整数 ,返回 这个重复的数 。
*
* 你设计的解决方案必须 不修改 数组 nums 且只用常量级 O(1) 的额外空间。
*
*
*
* 示例 1:
*
*
* 输入:nums = [1,3,4,2,2]
* 输出:2
*
*
* 示例 2:
*
*
* 输入:nums = [3,1,3,4,2]
* 输出:3
*
*
*
*
* 提示:
*
*
* 1 <= n <= 10^5
* nums.length == n + 1
* 1 <= nums[i] <= n
* nums 中 只有一个整数 出现 两次或多次 ,其余整数均只出现 一次
*
*
*
*
* 进阶:
*
*
* 如何证明 nums 中至少存在一个重复的数字?
* 你可以设计一个线性级时间复杂度 O(n) 的解决方案吗?
*
*
*/
// @lc code=start
class Solution {
public int findDuplicate(int[] nums) {
int slow = nums[0], fast = nums[nums[0]];
while (slow != fast) {
slow = nums[slow];
fast = nums[nums[fast]];
}
int i = 0, j = slow;
while (i != j) {
i = nums[i];
j = nums[j];
}
return i;
}
}
// @lc code=end