Skip to content

Commit 37d4e34

Browse files
refactor 442
1 parent b9d92aa commit 37d4e34

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

src/main/java/com/fishercoder/solutions/_442.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,20 @@ public List findDuplicates(int[] nums) {
2323
}
2424

2525
public static class Solution2 {
26-
//O(1) space
27-
//O(n) time
26+
/**
27+
* O(1) space
28+
* O(n) time
29+
*

30+
* This approach makes full use of what the problem states: all the integers of nums are in the range [1, n],
31+
* this implies that for any value x in this array, x - 1 must be a valid index in this array
32+
* thus, nums[x - 1] is a valid element in this array.
33+
*

34+
* So the solution was born:
35+
* we could mark one element as seen/visited before by negating it,
36+
* so when we encounter this same number again, i.e. the number is negative,
37+
* we know it appeared before, so we add it to the result
38+
* and then negate this number back.
39+
*/
2840
public List<Integer> findDuplicates(int[] nums) {
2941
List<Integer> result = new ArrayList();
3042
for (int i = 0; i < nums.length; i++) {
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._442;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import java.util.Arrays;
8+
9+
import static org.junit.Assert.assertEquals;
10+
11+
public class _442Test {
12+
private static _442.Solution1 solution1;
13+
private static _442.Solution2 solution2;
14+
15+
@BeforeClass
16+
public static void setup() {
17+
solution1 = new _442.Solution1();
18+
solution2 = new _442.Solution2();
19+
}
20+
21+
@Test
22+
public void test1() {
23+
assertEquals(Arrays.asList(2, 3), solution1.findDuplicates(new int[]{4, 3, 2, 7, 8, 2, 3, 1}));
24+
assertEquals(Arrays.asList(2, 3), solution2.findDuplicates(new int[]{4, 3, 2, 7, 8, 2, 3, 1}));
25+
}
26+
27+
}

0 commit comments

Comments
 (0)