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.优化实现,提高效率,参考其他的博客,有两种优化实现方法,下面一一列出:
排序数组,头索引和尾索引加和,向中间移动索引,直到加和等于目标数值。复杂度为排序的复杂度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]]
用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 0
- TwoSum--python
- twoSum
- TwoSum
- TwoSum
- TwoSum
- twoSum
- TwoSum
- TwoSum
- TwoSum
- TwoSum
- TwoSum
- twoSum
- TwoSum
- twoSum
- TwoSum
- TwoSum
- twosum
- TwoSum
- linux下的开源移动图像监测程序--motion编译与配置
- 扯淡
- Spring加载properties文件的两种方式
- 隐藏虚拟按键
- 内核中常用的双向链表数据结构(list_head)详解
- TwoSum--python
- GitChat·技术管理 | Cynefin 框架和不确定性管理思维
- JQuery学习笔记
- 快启动win10pe制作详细图文教程
- Android获取网络状态
- 自定义view的点击、长按、及长按手势监听事件
- Go数组与切片
- SharePreferences保存数据(附带工具类)
- 解决SQL Server 2008 错误15023:当前数据库中已存在用户或角色,SQLServer2008,错误15023 在使用SQL Server 2008时,我们经常会遇到一个