卖萌的弱渣

I am stupid, I am hungry.

Two Sum

Two Sum

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.

Example

numbers=[2, 7, 11, 15], target=9

return [1, 2]

Note

You may assume that each input would have exactly one solution

Challenge

Either of the following solutions are acceptable:

  • O(n) Space, O(nlogn) Time
  • O(n) Space, O(n) Time

Solution

  • Space: O(N), Time: O(nlogn)
(Two-Sum.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    """
    @param numbers : An array of Integer
    @param target : target = numbers[index1] + numbers[index2]
    @return : [index1 + 1, index2 + 1] (index1 < index2)
    """
    def twoSum(self, numbers, target):
        result = []
        hash_map = dict()
        if numbers == None:
            return result
        # Create hash_map: <numbers[i], i>
        for i in range(len(numbers)):
            hash_map[numbers[i]] = i+1

        for front in numbers:
            if hash_map.has_key(target-front) and hash_map[front] < hash_map[target-front]:
                result.append(hash_map[front])
                result.append(hash_map[target-front])
        return result
  • Space: O(N), Time: O(N) 先排序,两个指针,分别从头尾开始,向中间靠拢,直到发现目标
(Two-Sum2.py) download
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
32
33
34
35
36
37
38
39
40
41
class Solution:
    """ 
    @param numbers : An array of Integer 
    @param target : target = numbers[index1] + numbers[index2] 
    @return : [index1 + 1, index2 + 1] (index1 < index2) 
    Space: O(N)
    Time: O(N)
    """

    def twoSum(self, numbers, target):

        result = []
        # Create hash_map: [numbers[i], i]
        hash_map = dict()
        # sorted_array:
        sorted_array = sorted(numbers)

        # Create hash_map
        for i in range(len(numbers)):
            hash_map[numbers[i]] = i+1

        front = 0
        end = len(numbers)-1

        while front < end :
            if sorted_array[front]+sorted_array[end] < target:
                front += 1
            elif sorted_array[front]+sorted_array[end] > target:
                end -=1
            else:
                # Real index is stored in hash_map
                first = hash_map[sorted_array[front]]
                second = hash_map[sorted_array[end]]
                if first < second:
                    result.append(first)
                    result.append(second)
                else:
                    result.append(second)
                    result.append(first)

                return result