-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindTheDuplicateNumber287.java
More file actions
32 lines (30 loc) · 1.04 KB
/
Copy pathFindTheDuplicateNumber287.java
File metadata and controls
32 lines (30 loc) · 1.04 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
/*
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
You must solve the problem without modifying the array nums and uses only constant extra space.
*/
public class FindTheDuplicateNumber287 {
public static void main(String[] args) {
System.out.println(findDuplicate(new int[]{1, 3, 4, 2, 2}));
System.out.println(findDuplicate(new int[]{3, 1, 3, 4, 2}));
}
public static int findDuplicate(int[] nums) {
int slow = nums[0], fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
// int[] dict = new int[nums.length];
// for (int num : nums) {
// if (dict[num] == 1) return num;
// dict[num] = 1;
// }
// return 0;
}
}