|
2 | 2 |
|
3 | 3 |
|
4 | 4 | def threeNumberSum(array, targetSum):
|
5 |
| - items = dict(Counter(array)) |
6 |
| - for item1, counter1 in items.items(): |
7 |
| - if counter1 > 0: |
8 |
| - for item2, counter2 in items.items(): |
9 |
| - item3_expected = targetSum - item1 - item2 |
10 |
| - if (item1 == item2 or item1 == item3_expected or item2 == item3_expected) and counter2 < 2: |
11 |
| - continue |
12 |
| - if item3_expected in items: |
13 |
| - print(item1, item2, item3_expected) |
| 5 | + array.sort() # nlogn |
| 6 | + results = [] |
| 7 | + for current in range(len(array)): |
| 8 | + left = current + 1 |
| 9 | + right = len(array) - 1 |
| 10 | + while left < right: |
| 11 | + result = array[current] + array[left] + array[right] |
| 12 | + if result == targetSum: |
| 13 | + results.append([array[current], array[left], array[right]]) |
| 14 | + left += 1 |
| 15 | + right -= 1 |
| 16 | + elif result < targetSum: |
| 17 | + left += 1 |
| 18 | + else: |
| 19 | + right -= 1 |
| 20 | + return results |
14 | 21 |
|
15 | 22 |
|
16 | 23 | if __name__ == '__main__':
|
17 |
| - threeNumberSum([12, 3, 1, 2, -6, 5, -8, 6], 0) |
| 24 | + print(threeNumberSum([12, 3, 1, 2, -6, 5, -8, 6], 0)) |
| 25 | + print(threeNumberSum([1, 2, 3, 4, 5, 6, 7, 8, 9, 15], 33)) |
| 26 | + print(threeNumberSum([1], 10)) |
| 27 | + print(threeNumberSum([1, 2, 3, 7, 0], 10)) |
0 commit comments