简体   繁体   中英

Find 3 elements in sorted array that sum up to 0 (a+b+c = 0)

Is there any better solution than the obvious O(n^3)? I can use one element multiple times so for an array {-1, 0, 2} there is a solution: (-1, -1, 2) or (0, 0, 0).

The classic 3SUM problem can be solved in O(n^2). This can also be solved with O(n^2)

# assume arr is sorted and doesn't contain duplicates

out = []
s = set(arr)
for i in range(len(arr)):
    for j in range(i, len(arr)):
        a = - (arr[i] + arr[j])
        if a >= arr[j] and a in s:
            out.append((arr[i], arr[j], a))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM