Number of Ways Where Square of Number Is Equal to Product of Two Numbers LeetCode solution in Java

1
class Solution {
2
public int numTriplets(int[] nums1, int[] nums2) {
3
Arrays.sort(nums1);
4
Arrays.sort(nums2);
5
return count(nums1, nums2) + count(nums2, nums1);
6
}
7

8
public int count(int a[], int b[]) {
9
int n = a.length;
10
int m = b.length;
11
int count = 0;
12
for (int i = 0; i < n; i++) {
13
long x = (long) a[i] * a[i];
14
int j = 0;
15
int k = m - 1;
16
while (j < k) {
17
long prod = (long) b[j] * b[k];
18
if (prod < x) j++;
19
else if (prod > x) k--;
20
else if (b[j] != b[k]) {
21
int jNew = j;
22
int kNew = k;
23

24
while (b[j] == b[jNew]) jNew++;
25
while (b[k] == b[kNew]) kNew--;
26
count += (jNew - j) * (k - kNew);
27
j = jNew;
28
k = kNew;
29
} else {
30
int q = k - j + 1;
31
count += (q) * (q - 1) / 2;
32
break;
33
}
34
}
35
}
36
return count;
37
}
38
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0