Created
October 9, 2017 03:22
-
-
Save vetional/ae0d1a3f4396ef2cd5563388a903c6e0 to your computer and use it in GitHub Desktop.
3sum problem created by vetional - https://repl.it/MS4f/0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Determine if any 3 integers in an array sum to 0. | |
# For example, for array [4, 3, -1, 2, -2, 10], the function should return true since 3 + (-1) + (-2) = 0. To make things simple, each number can be used at most once. | |
def solution(A): | |
A.sort() # O(nlogn) | |
print A | |
for i, x in enumerate(A): # O(n**2) | |
start = 0 | |
end = len(A) - 1 | |
while start < end: | |
# make sure the start or end | |
# is not the currrent number | |
if start == i: | |
start += 1 | |
if end == i: | |
end -= 1 | |
s = A[start] + A[end] | |
print start, end, s, -1 * x | |
if s == -1 * x: | |
print "found: ", A[start] , A[end], x | |
return True | |
if s > -1 * x: | |
end -= 1 | |
elif s < -1 * x: | |
start += 1 | |
return False | |
A = [4, 3, -1, 2, -2, 10] | |
print solution(A) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment