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 44import java .util .Set ;
55
66/**
7+ * 287. Find the Duplicate Number
8+ *
79 * Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
810 * prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
9-
11+ *
1012 Note:
1113 You must not modify the array (assume the array is read only).
1214 You must use only constant, O(1) extra space.
@@ -16,20 +18,23 @@ Your runtime complexity should be less than O(n2).
1618 */
1719public class _287 {
1820
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+ }
2731 }
32+ return dup ;
2833 }
29- return dup ;
3034 }
3135
32- class SolutionO1 {
36+ public static class Solution2 {
37+ /** O(1) space */
3338 public int findDuplicate (int [] nums ) {
3439 int slow = 0 ;
3540 int fast = 0 ;
You can’t perform that action at this time.
0 commit comments