Skip to content

Commit b5f48f3

Browse files
committed
[hackerrank] "Triple sum" 성능 개선 버전
1 parent e1cb6fe commit b5f48f3

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

src/main/kotlin/hackerrank/search/TripleSum.java

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,47 @@
11
package hackerrank.search;
22

33
import java.util.Arrays;
4-
import java.util.HashSet;
5-
import java.util.Set;
64

75
public class TripleSum {
86

97
static long triplets(int[] a, int[] b, int[] c) {
108

11-
// 예제로만 보면 주어진 배열들이 정렬되어 있음. 하지만 설명에는 명시되어 있지 않음.
129
Arrays.sort(a);
1310
Arrays.sort(b);
1411
Arrays.sort(c);
1512

13+
long aCount = 0;
14+
long cCount = 0;
15+
int aIndex = 0;
16+
int cIndex = 0;
1617
long count = 0L;
17-
final Set<Integer> calculated = new HashSet<>();
18+
int bCurrent = 0;
1819

19-
// 배열 안에 중복된 숫자가 있을 수 있음.
20-
for (int number : b) {
20+
for (int n : b) {
2121

22-
if (calculated.contains(number)) continue;
23-
calculated.add(number);
22+
// 같은 값이 존재할 수 있음.
23+
if (n <= bCurrent) continue;
24+
bCurrent = n;
2425

25-
final long left = Arrays.stream(a).filter(x -> x <= number).count();
26-
final long right = Arrays.stream(c).filter(x -> x <= number).count();
27-
count += left * right;
26+
while (aIndex < a.length && a[aIndex] <= n) {
27+
// 같은 값이 존재할 수 있음.
28+
if (aIndex == 0 || a[aIndex - 1] != a[aIndex]) {
29+
aCount++;
30+
}
2831

32+
aIndex++;
33+
}
34+
35+
while (cIndex < c.length && c[cIndex] <= n) {
36+
// 같은 값이 존재할 수 있음.
37+
if (cIndex == 0 || c[cIndex - 1] != c[cIndex]) {
38+
cCount++;
39+
}
40+
41+
cIndex++;
42+
}
43+
44+
count += aCount * cCount;
2945
}
3046

3147
return count;

0 commit comments

Comments
 (0)