Ejemplo n.º 1
0
 def test_two_sum(self):
     array = [2, 7, 11, 15]
     # test two_sum
     self.assertEqual([1, 2], two_sum(array, 9))
     self.assertEqual([2, 4], two_sum(array, 22))
     # test two_sum1
     self.assertEqual([1, 2], two_sum1(array, 9))
     self.assertEqual([2, 4], two_sum1(array, 22))
     # test two_sum2
     self.assertEqual([1, 2], two_sum2(array, 9))
     self.assertEqual([2, 4], two_sum2(array, 22))
Ejemplo n.º 2
0
"""
Given an array of integers that is already sorted in ascending order, find two
numbers such that they add up to a specific target number. The function two_sum
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 and you
may not use the same element twice.
Input: numbers = [2, 7, 11, 15], target=9
Output: index1 = 1, index2 = 2
Solution:
two_sum: using binary search
two_sum1: using dictionary as a hash table
two_sum2: using two pointers
"""
from algorithms.search import two_sum, two_sum1, two_sum2
numbers = [2, 7, 11, 15]

target = 9

print(two_sum(numbers, target))

print(two_sum1(numbers, target))

print(two_sum2(numbers, target))