-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode287.java
More file actions
71 lines (65 loc) · 1.79 KB
/
LeetCode287.java
File metadata and controls
71 lines (65 loc) · 1.79 KB
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
import java.util.HashSet;
public class LeetCode287 {
public static void main(String[] args) {
// 输入:nums = [1,3,4,2,2]
// 输出:2
System.out.println(new Solution287_4().findDuplicate(new int[] { 1, 3, 4, 2, 2 }));
// 输入:nums = [3,1,3,4,2]
// 输出:3
System.out.println(new Solution287_4().findDuplicate(new int[] { 3, 1, 3, 4, 2 }));
}
}
class Solution287_1 {
// NOTE: 这个只能解决某个值重复两次的情况
public int findDuplicate(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
sum -= i;
}
return sum;
}
}
class Solution287_2 {
// NOTE: 时间复杂度为O(n^2)
public int findDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) {
return nums[i];
}
}
}
return -1;
}
}
class Solution287_3 {
// NOTE: 空间复杂度为O(n)
public int findDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
if (set.contains(nums[i])) {
return nums[i];
} else {
set.add(nums[i]);
}
}
return -1;
}
}
class Solution287_4 {
// NOTE: 快慢指针检测环
public int findDuplicate(int[] nums) {
int slow = 0, fast = 0;
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
slow = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
}