简繁EN

LeetCodeNo. 105

[LeetCode with Python] 1. Two Sum

Contents

Problem

Problem page: https://leetcode.com/problems/two-sum/
Topics: Array, Hash Table
Difficulty: Medium
Similar problems: (M) 3Sum, (M) 4Sum, (M) Two Sum II - Input array is sorted, (E) Two Sum III - Data structure design

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


Analysis

Given an array (which isn't necessarily sorted) and a value target, find two numbers in the array that add up to exactly target. Return their indices (the array indices start at 1, not 0).
First, sort the array. Since we need the original indices of the two numbers, not the numbers themselves, wrap each element in a new Item object that also stores its original index. Sort by the elements' values, then use two pointers: set index1 to the first element of the sorted array and index2 to the last. If the two numbers they point to add up to target, the search is over. If the sum is less than target, index2 already points to the largest number in the array, so the only option is to move index1 one step to the right. When the sum exceeds target, the only possible move is to shift index2 one step to the left because index1 already points to the smallest number in the array. Repeat this in a loop until the sum equals target and the search succeeds, or index1>=index2 and the search fails.
The space complexity is O(n) because we build a new sequence of Item objects. As for time complexity, if we assume Python's sort uses quicksort, sorting takes O(n*logn) time and the search takes O(n), so the total time complexity is O(n*logn).
The input array might have length 0, in which case the search fails no matter what target is. The example in the problem is misleading: if you're not paying attention, you might think the input array is already sorted. Also, the array indices start at 1, not 0.
Still, it bothers me a bit that this algorithm has to sort the array first. Is there a better algorithm?


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:

class Item:
def __init__(self, value, index):
self.value = value
self.index = index

# @return a tuple, (index1, index2)
def twoSum(self, num, target):
len_num = len(num)
if 0 == len_num:
return (-1, -1)

items = [Solution.Item(value, 0) for value in num]
for i in range(0, len_num):
items[i].index = i + 1
items.sort(lambda x, y: cmp(x.value, y.value))
index1 = 0
index2 = len_num - 1
is_find = False
while index1 < index2:
total = items[index1].value + items[index2].value
if total < target:
index1 += 1
elif total > target:
index2 -= 1
else:
is_find = True
break
(index1, index2) = (index1, index2) if items[index1].index <= items[index2].index else (index2, index1)
return (items[index1].index, items[index2].index) if is_find else (-1, -1)

Article link: https://xnerv.wang/en/leetcode-two-sum/