TwoSum--python

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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值