given 2 array t and j simplify t[i]*t[j]=s[i]+s[j]...
تم الإنشاء في: ١٢ يوليو ٢٠٢٥
تمت الإجابة باستخدام O4 Mini High بواسطة Chat01
تم الإنشاء في: ١٢ يوليو ٢٠٢٥
تمت الإجابة باستخدام O4 Mini High بواسطة Chat01
given 2 array t and j
simplify t[i]*t[j]=s[i]+s[j] so that we can solve it in O(n)
tell me approach or code in java
Here’s a slick way to turn
t[i] * t[j] = s[i] + s[j]
into an O(n) scan (assuming you’re happy with O(n log n) for an initial sort, or O(n) if 𝑡 is already in non-decreasing order):
Zip and sort
Build an array of triples
javaclass P { int t, s, idx; /* original index if you need it */ }
and sort it by t
ascending. If t
is already sorted, you can skip this step.
Two‐pointer walk
Now set
int L = 0, R = n-1;
and while L < R
:
javalong prod = 1L*P[L].t * P[R].t; long sum = P[L].s + P[R].s;
prod < sum
, you need more on the left ⇒ L++
prod > sum
, you need less on the right ⇒ R--
prod == sum
), you’ve found a solution (L,R)
. Record it (e.g. in a list) and then advance both pointers (or handle duplicates as needed).This is exactly the same pattern as the classic “two‐sum on a sorted array” and runs in O(n) once the data is sorted (O(n log n) total if you need that sort).
javaimport java.util.*; public class PairFinder { static class P { int t, s, idx; P(int t, int s, int idx) { this.t = t; this.s = s; this.idx = idx; } } public static List<int[]> findAll(int[] t, int[] s) { int n = t.length; List<P> A = new ArrayList<>(n); for (int i = 0; i < n; i++) { A.add(new P(t[i], s[i], i)); } // sort by t ascending Collections.sort(A, Comparator.comparingInt(a -> a.t)); List<int[]> res = new ArrayList<>(); int L = 0, R = n - 1; while (L < R) { long prod = 1L * A.get(L).t * A.get(R).t; long sum = A.get(L).s + A.get(R).s; if (prod < sum) { L++; } else if (prod > sum) { R--; } else { // found one; save original indices if you like res.add(new int[]{ A.get(L).idx, A.get(R).idx }); // move both pointers past this match L++; R--; } } return res; } public static void main(String[] args) { int[] t = { 2, 3, 5, 7 }; int[] s = { 3, 8,17,26 }; // e.g. 2*7 = 3+26 = 29, 3*5 = 8+17 = 25, etc. List<int[]> pairs = findAll(t, s); for (int[] p : pairs) { System.out.printf("i=%d, j=%d\n", p[0], p[1]); } } }
Why it’s O(n):
L
or R
, so at most 2n steps ⇒ O(n).This pattern generalizes any time you have
A[i] + A[j] ?= someMonotonicFunctionOf(i,j)
and you can order your data so those two moving‐pointers capture the monotonicity.