TwoSum--python

来源:互联网 发布:java开发简历范文 编辑:程序博客网 时间:2024/06/09 15:53

1.TowSum

问题描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

>样例Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

解题过程:
1.初学算法遇到这问题第一反应是做两两相加,循环遍历,时间复杂度O(n^2),这个方法效率很低代码如下:

def towsum(self,num,target):  for i in range(len(num) - 1):      target = target - num[i]      for j  in range(i + 1,len(num)):          if num[j] == target:              return [i,j]

2.优化实现,提高效率,参考其他的博客,有两种优化实现方法,下面一一列出:

  1. 排序数组,头索引和尾索引加和,向中间移动索引,直到加和等于目标数值。复杂度为排序的复杂度O(nlog(n))加上比较的复杂度O(n)

    def twosum(self,num,target):    nums = sorted(num)    a = 0    b = len(nums) - 1    index = []    while a < b:        if nums[a] + nums[b] < target:            a = a + 1        elif nums[a] + nums[b] > target:            b = b - 1        elif nums[a] + nums[b] == target:            print(nums[a],nums[b])            for i in range(len(num)):                if nums[a] == num[i]:                    index.append(i)                    break            for j in range(len(num) - 1,-1,-1):                if nums[b] == num[j]:                    index.append(j)                    break            index = sorted(index)            break    return [index[0],index[1]]
  2. 用python的字典,也就是哈希,在字典里面加入数组里面的数字,并查找数字,如果查找到就是匹配上了。这个方法我很难想到,对字典的操作,很巧妙,代码简洁,时间复杂度为O(n)代码如下:

    dict = {}for i in range(len(num)):   x = num[i]   if target - x in dict:      return (dict[target - x], i)   dict[x] = i
原创粉丝点击