سوال ۶۷ کنکور ارشد علوم کامپیوتر ۱۳۹۷
میخواهیم در یک آرایه از اعداد صحیح به طول اندیسهای و و را پیدا کنیم که باشد. بهترین زمان ممکن برای این کار کدام است؟
پاسخ صحیح: گزینهٔ A —
We must decide whether three indices exist with
Reduce to a 3SUM-type problem. Define a new array of squares, computed in . The goal becomes: find indices with .
Sort the squares. Sort in . Since all squares are non-negative, this is a clean ordered list of candidate target values.
Two-pointer scan per target. Fix the largest element of a triple as the target . With sorted, search for two values that sum to using the two-pointer technique:
for each k: # choose the target a[k]
lo = 0, hi = n-1
while lo < hi:
s = a[lo] + a[hi]
if s == a[k]: report (lo, hi, k); done
elif s < a[k]: lo += 1
else: hi -= 1
Each two-pointer pass costs , and we run it for each of the choices of :
Why not faster? This is a Pythagorean-triple search, a special case of the 3SUM problem (). 3SUM is widely believed to require (no sub-quadratic algorithm is known), so among the offered choices the achievable optimum is
The naive triple loop is (option 2), the of binary-searching each pair (option 3) is beaten by the two-pointer scan, and (option 4) is below the conjectured 3SUM bound — unattainable.
Exam trick: Any "find in an array" task squashes to sort + two pointers, giving — strictly better than per-pair binary search () and the brute-force .