两数之和

思路:有两种方法。第一种方法是用两重循环,遍历计算所有可能的target的值,这是比较朴素的方法。另外一种方法是利用hash表。现将所有的值保存到hash表中,然后计算target减去当前的value的值,然后这个值在hash表中并且不是当前的value,那么就找到了答案。

第一种方法:

def two_sum_native(nums, target):
    """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
    """
    num_len = len(nums)
    for i in range(num_len):
        num1 = nums[i]
        for j in range(i + 1, num_len):
            num2 = nums[j]
            sum = num1 + num2
            if sum == target:
                indice = [i, j]
                return indice
    return "the input is illegal"

第二种方法:

def two_sum_hash(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash_array = {}
for i in range(len(nums)):
hash_array[nums[i]] = i
for i in range(len(nums)):
left = target - nums[i]
if left in hash_array.keys() and hash_array.get(left) != i:
return [i, hash_array.get(left)]
return "the input is illegal"

我写了一个测试函数,在本地的测试结果如下:

def test_function():
    times = 1000
    right = 0
    for time in range(times):
        len = random.randint(0, 1000)
        array = []
        for i in range(len):
            array.append(random.randint(0, 1000))
        array_set = list(set(array))
        target = random.randint(0, 10000)
        myvalue = two_sum_hash(array_set, target)
        true_value = two_sum_native(array_set, target)
        if myvalue == true_value:
            right += 1
    return float(right)/float(times)

运行结果:

我有在leetcode上提交了这两种方法,比较这二者的执行时间:

第一种方法:

 第二种方法:

第二种方法相比于第一种方法虽然提高的不是很多,但至少还是提高了的。

原文地址:https://www.cnblogs.com/whatyouknow123/p/9214749.html