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
| // @Title: 寻找重复数 (Find the Duplicate Number)
// @Author: 15816537946@163.com
// @Date: 2019-11-12 11:52:52
// @Runtime: 8 ms
// @Memory: 3.8 MB
/*
* @lc app=leetcode.cn id=287 lang=golang
*
*
* [287] 寻找重复数
* https://leetcode-cn.com/problems/find-the-duplicate-number/description/
*
* algorithms
* Medium (60.57%)
* Likes: 253
* Dislikes: 0
* Total Accepted: 18.2K
* Total Submissions: 30K
* Testcase Example: '[1,3,4,2,2]'
*
* 给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和
* n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
*
* 示例 1:
*
* 输入: [1,3,4,2,2]
* 输出: 2
*
*
* 示例 2:
*
* 输入: [3,1,3,4,2]
* 输出: 3
*
*
* 说明:
*
*
* 不能更改原数组(假设数组是只读的)。
* 只能使用额外的 O(1) 的空间。
* 时间复杂度小于 O(n^2) 。
* 数组中只有一个重复的数字,但它可能不止重复出现一次。
*
*
*/
// 快慢指针
func findDuplicate(nums []int) int {
slow, fast := nums[0], nums[nums[0]]
for slow != fast {
slow, fast = nums[slow], nums[nums[fast]]
}
slow = 0
for slow != fast {
slow, fast = nums[slow], nums[fast]
}
return slow
}
|