Java Simple sort
An easy way to sort and count:\n1, sort all arrays by non-decreasing order;\n2, for each i, shrink from left and right as j and k, then find each triples\n3, ha
An easy way to sort and count:\n1, sort all arrays by non-decreasing order;\n2, for each i, shrink from left and right as j and k, then find each triples\n3, handle special case for  dups, such as[1, 1], [1, 1, 1]\nTime: O(M*N)\nSpace: O(1)\n\n```\nclass Solution {\n    public int numTriplets(int[] a, int[] b) {\n        Arrays.sort(a);\n        Arrays.sort(b);\n        return cnt(a, b) + cnt(b, a);\n    }\n    \n    private int cnt(int[] a, int[] b) {\n        int res = 0, m = a.length, n = b.length;\n        for (int i = 0; i < m; i++) {\n            long t = ((long) a[i]) * ((long) a[i]);\n            for (int l = 0, r = n - 1; l < n - 1; l++) { // finding pairs for i, l, r;\n                if (((long) b[l]) * ((long) b[r]) < t) continue;\n                while (r >= l && ((long) b[l]) * ((long) b[r]) > t) r--;\n                if (r <= l) break;\n                if (((long) b[l]) * ((long) b[r]) == t) {\n                    int orig = r;\n                    while(r > l && b[r] == b[orig]) {  // [1, 1], [1, 1, 1]\n                        r--;\n                        res++;\n                    }\n                    r = orig;  // reset to next cont;\n                }\n            }\n        }\n        return res;\n    }\n}\n```\n\nThere is a better solution to use HashMap turn the l, r findings to O(n) 2-sum ones:\nThat is straightforward and easy understanding.\nAnother good point is that you don\'t have to sort the arrays.\nTime: O(M * N)\nspace: O(max(M, N));\n```\nclass Solution {\n    public int numTriplets(int[] a, int[] b) {\n        return cnt(a, b) + cnt(b, a);\n    }\n    \n    private int cnt(int[] a, int[] b) {\n        int res = 0, m = a.length;\n        for (int i = 0; i < m; i++) {\n            Map<Long, Integer> map = new HashMap<>();\n            long t = ((long) a[i]) * ((long) a[i]);\n            for (long n : b) {  //must transferred to long\n                if (t % n == 0) res += map.getOrDefault(t / n, 0); //new pair formed btw n and previous found t / n\n                map.put(n, map.getOrDefault(n, 0) + 1); // cached the count found;\n            }\n        }\n        return res;\n    }\n}\n```\n\n
[]