Number of Ways Where Square of Number Is Equal to Product of Two Numbers LeetCode solution in Java
1class Solution {2public int numTriplets(int[] nums1, int[] nums2) {3Arrays.sort(nums1);4Arrays.sort(nums2);5return count(nums1, nums2) + count(nums2, nums1);6}78public int count(int a[], int b[]) {9int n = a.length;10int m = b.length;11int count = 0;12for (int i = 0; i < n; i++) {13long x = (long) a[i] * a[i];14int j = 0;15int k = m - 1;16while (j < k) {17long prod = (long) b[j] * b[k];18if (prod < x) j++;19else if (prod > x) k--;20else if (b[j] != b[k]) {21int jNew = j;22int kNew = k;2324while (b[j] == b[jNew]) jNew++;25while (b[k] == b[kNew]) kNew--;26count += (jNew - j) * (k - kNew);27j = jNew;28k = kNew;29} else {30int q = k - j + 1;31count += (q) * (q - 1) / 2;32break;33}34}35}36return count;37}38}