Created
February 17, 2017 04:33
-
-
Save boris-42/c64158bbf79058e3ff8ef3f792f06caf to your computer and use it in GitHub Desktop.
This file contains 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
class Solution: | |
# @param A : list of integers | |
# @param B : integer | |
# @return an integer | |
def threeSumClosest(self, A, B): | |
A.sort() | |
if len(A) == 3: | |
return sum(A) | |
i = 0 | |
j = 1 | |
k = len(A) - 1 | |
def calc(ii=None, jj=None, kk=None): | |
return A[ii or i] + A[jj or j] + A[kk or k] | |
best_result = calc() | |
def min_(new_result, best_result): | |
if abs(new_result - B) < abs(best_result - B): | |
return new_result | |
return best_result | |
while True: | |
r = calc() | |
old = [i, j, k] | |
if best_result == B: | |
return best_result | |
elif r > B: | |
while j + 1 < k and calc() >= B: | |
k -= 1 | |
best_result = min_(calc(), best_result) | |
while j + 1 < k and calc(jj=j + 1) <= B: | |
j += 1 | |
best_result = min_(calc(), best_result) | |
else: | |
while j + 1 < k and calc(jj=j + 1) <= B: | |
j += 1 | |
best_result = min_(calc(), best_result) | |
while calc() <= B: | |
if i + 1 < j: | |
i += 1 | |
elif j + 1 < k: | |
j += 1 | |
else: | |
break | |
best_result = min_(calc(), best_result) | |
while j - 1 > i and calc(jj=j - 1) >= B: | |
j -= 1 | |
best_result = min_(calc(), best_result) | |
if old == [i, j, k]: | |
break | |
return int(best_result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment