-
Notifications
You must be signed in to change notification settings - Fork 870
/
TripleSum.java
95 lines (77 loc) · 1.95 KB
/
TripleSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
*
* Problem Statement-
* [Triple sum](https://www.hackerrank.com/challenges/triple-sum/problem)
* [Tutorial](https://youtu.be/pVkHLciuank)
*
*/
package com.javaaid.search;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class TripleSum {
static long triplets(int[] a, int[] b, int[] c) {
long distinctTripletCount = 0;
int[] distinctA = removeDuplicates(a);
int[] distinctB = removeDuplicates(b);
int[] distinctC = removeDuplicates(c);
Arrays.sort(distinctA);
Arrays.sort(distinctB);
Arrays.sort(distinctC);
for (int q : distinctB) {
long c1 = getValidIndex(distinctA, q) + 1;
long c3 = getValidIndex(distinctC, q) + 1;
distinctTripletCount += c1 * c3;
}
return distinctTripletCount;
}
private static int[] removeDuplicates(int[] a) {
Set<Integer> set = new HashSet<>();
for (int item : a) {
set.add(item);
}
int len = set.size();
int result[] = new int[len];
int i = 0;
for (int item : set) {
result[i++] = item;
}
return result;
}
static int getValidIndex(int[] distinctA, int key) {
int low = 0;
int high = distinctA.length - 1;
int count = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (distinctA[mid] <= key) {
count = mid;
low = mid + 1;
} else
high = mid - 1;
}
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int lena = sc.nextInt();
int lenb = sc.nextInt();
int lenc = sc.nextInt();
int a[] = new int[lena];
int b[] = new int[lenb];
int c[] = new int[lenc];
for (int i = 0; i < lena; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < lenb; i++) {
b[i] = sc.nextInt();
}
for (int i = 0; i < lenc; i++) {
c[i] = sc.nextInt();
}
long result = triplets(a, b, c);
System.out.println(result);
sc.close();
}
}