|
| 1 | + |
| 2 | +''' |
| 3 | +Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? |
| 4 | +Find all unique triplets in the array which gives the sum of zero. |
| 5 | +
|
| 6 | +Note: |
| 7 | +Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c) |
| 8 | +
|
| 9 | +The solution set must not contain duplicate triplets. |
| 10 | + For example, given array S = {-1 0 1 2 -1 -4}, |
| 11 | +
|
| 12 | + A solution set is: |
| 13 | + (-1, 0, 1) |
| 14 | + (-1, -1, 2) |
| 15 | +
|
| 16 | +''' |
| 17 | +def binary_search(array, value): |
| 18 | + low, high = 0, len(array) |
| 19 | + while low < high: |
| 20 | + mid = (low + high) / 2 |
| 21 | + midval = array[mid] |
| 22 | + if midval < value: |
| 23 | + low = mid+1 |
| 24 | + elif midval > value: |
| 25 | + high = mid |
| 26 | + else: |
| 27 | + return mid |
| 28 | + |
| 29 | + return None |
| 30 | + |
| 31 | +class Solution: |
| 32 | + # @return a list of lists of length 3, [[val1,val2,val3]]\ |
| 33 | + def threeSum(self, num): |
| 34 | + mapping = [] |
| 35 | + num.sort() |
| 36 | + numLen = len(num) |
| 37 | + |
| 38 | + for i in range(numLen): |
| 39 | + if num[i] == num[i-1] and i != 0: |
| 40 | + continue |
| 41 | + if num[i] > 0: |
| 42 | + break |
| 43 | + |
| 44 | + for j in range(i + 1, numLen): |
| 45 | + j = numLen + i - j |
| 46 | + |
| 47 | + if j + 1 != numLen and num[j] == num[j+1]: |
| 48 | + continue |
| 49 | + |
| 50 | + needed = 0-num[i]-num[j] |
| 51 | + if needed < num[i]: |
| 52 | + continue |
| 53 | + if needed > num[j]: |
| 54 | + break |
| 55 | + |
| 56 | + if binary_search(num[i+1:j], needed) != None: |
| 57 | + mapping.append([num[i], needed, num[j]]) |
| 58 | + |
| 59 | + return mapping |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == '__main__': |
| 63 | + rst = Solution().threeSum([-2, -1, 0, 1, 2, 3]) |
| 64 | + rst.sort() |
| 65 | + print rst |
| 66 | + print Solution().threeSum([]) |
0 commit comments