File tree Expand file tree Collapse file tree 1 file changed +16
-11
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +16
-11
lines changed Original file line number Diff line number Diff line change 4
4
import java .util .Set ;
5
5
6
6
/**
7
+ * 287. Find the Duplicate Number
8
+ *
7
9
* Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
8
10
* prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
9
-
11
+ *
10
12
Note:
11
13
You must not modify the array (assume the array is read only).
12
14
You must use only constant, O(1) extra space.
@@ -16,20 +18,23 @@ Your runtime complexity should be less than O(n2).
16
18
*/
17
19
public class _287 {
18
20
19
- //no-brainer, used O(n) space
20
- public int findDuplicate (int [] nums ) {
21
- Set <Integer > set = new HashSet <>();
22
- int dup = 0 ;
23
- for (int i = 0 ; i < nums .length ; i ++) {
24
- if (!set .add (nums [i ])) {
25
- dup = nums [i ];
26
- break ;
21
+ public static class Solution1 {
22
+ /**no-brainer, used O(n) space*/
23
+ public int findDuplicate (int [] nums ) {
24
+ Set <Integer > set = new HashSet <>();
25
+ int dup = 0 ;
26
+ for (int i = 0 ; i < nums .length ; i ++) {
27
+ if (!set .add (nums [i ])) {
28
+ dup = nums [i ];
29
+ break ;
30
+ }
27
31
}
32
+ return dup ;
28
33
}
29
- return dup ;
30
34
}
31
35
32
- class SolutionO1 {
36
+ public static class Solution2 {
37
+ /** O(1) space */
33
38
public int findDuplicate (int [] nums ) {
34
39
int slow = 0 ;
35
40
int fast = 0 ;
You can’t perform that action at this time.
0 commit comments