Skip to content

Commit 8221b49

Browse files
optimize algorithm sand save space for 1200
1 parent 5436659 commit 8221b49

File tree

2 files changed

+19
-12
lines changed

2 files changed

+19
-12
lines changed

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

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import java.util.ArrayList;
44
import java.util.Arrays;
55
import java.util.List;
6-
import java.util.TreeMap;
76

87
/**
98
* 1200. Minimum Absolute Difference
@@ -39,20 +38,20 @@ public static class Solution1 {
3938
* */
4039
public List<List<Integer>> minimumAbsDifference(int[] arr) {
4140
Arrays.sort(arr);
42-
TreeMap<Integer, List<List<Integer>>> map = new TreeMap<>();
43-
for (int i = 0; i < arr.length - 1; i++) {
41+
int minimumDiff = arr[1] - arr[0];
42+
List result = new ArrayList();
43+
result.add(Arrays.asList(arr[0], arr[1]));
44+
for (int i = 1; i < arr.length - 1; i++) {
4445
int diff = arr[i + 1] - arr[i];
45-
if (map.containsKey(diff)) {
46-
List list = map.get(diff);
47-
list.add(Arrays.asList(arr[i], arr[i + 1]));
48-
map.put(diff, list);
49-
} else {
50-
List list = new ArrayList<>();
51-
list.add(Arrays.asList(arr[i], arr[i + 1]));
52-
map.put(diff, list);
46+
if (minimumDiff == diff) {
47+
result.add(Arrays.asList(arr[i], arr[i+1]));
48+
} else if (minimumDiff > diff) {
49+
minimumDiff = diff;
50+
result = new ArrayList();
51+
result.add(Arrays.asList(arr[i], arr[i+1]));
5352
}
5453
}
55-
return map.firstEntry().getValue();
54+
return result;
5655
}
5756
}
5857
}

src/test/java/com/fishercoder/_1200Test.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,12 @@ public void test1() {
3030
assertEquals(expected, solution1.minimumAbsDifference(arr));
3131
}
3232

33+
@Test
34+
public void test2() {
35+
arr = new int[]{40, 11, 26, 27, -20};
36+
expected = new ArrayList<>();
37+
expected.add(Arrays.asList(26, 27));
38+
assertEquals(expected, solution1.minimumAbsDifference(arr));
39+
}
40+
3341
}

0 commit comments

Comments
 (0)