Two Sum
2016-01-18 17:35
253 查看
Two Sum
这道题是进入leetcode的第一道题目,大致的思路最开始就是暴力解法,将数组中的每两个数相加,然后和target相比,计算了下复杂度,大概在O(n2)。换个思路,用target减去当前的数,在从数组中查询是否存在这个数。但是没有想到hash的办法,导致其实复杂度还是在O(n2)。但也通过了测试,看了网上有很多种办法,可以逐一学习一下。主要的方法有两种:
1. 先排序然后用双指针向中间夹逼,复杂度O(nlogn)
2. 用Map记录出现过的数,查找有没有跟当前的数构成target,复杂度为O(nlogn)。相对于自己直接的比较,还是用了hash比较快
方法一,跑下来的速度在40ms
class Solution(object): def twoSum(self, nums, target): nums_sorted = sorted(nums) left = 0 right = len(nums) - 1 while True: if nums_sorted[left] + nums_sorted[right] == target: post1 = nums.index(nums_sorted[left]) post2 = nums.index(nums_sorted[right]) if post2 == post1: post2 = nums[post1+1:].index(nums_sorted[right]) + post1 + 1 return min(post1+1, post2+1), max(post1+1, post2+1) elif nums_sorted[left] + nums_sorted[right] < target: left += 1 elif nums_sorted[left] + nums_sorted[right] > target: right -= 1
方法二,跑下来的速度在48ms反而慢了些
class Solution(object): def twoSum(self, nums, target): map = {} for i, value in enumerate(nums): if target-value in map: return map[target-value]+1, i+1 else: map[value] = i
相关文章推荐
- RecyclerView的万能分割线
- web应用的乱码解决
- php 5.6以上可以采用new PDD连接数据库的方法。
- Oracle创建DataBase Links
- Android活动(Activity)状态与生命周期总结
- 程序猿人们、媛媛们精神分裂的9件事
- Linux C串口编程部分 转
- nginx 重写 rewrite 基础及实例
- 自动化专业出路-前景-就业方向
- 在电脑上用麦克风录音声音明显小于实际声音
- iOS 日期与字符串格式互转
- iOS url编码、解码
- git add
- 360加固动态脱壳
- 输入一个无符号整数,用最少的步骤将该数变为1
- 树莓派 原理图 摄像头接口定义
- setw和setfill控制输出间隔
- 在centos 6.2,python2.7 下安装QT 4.8.3,pyqt 4.9.5 详细步骤
- MongoDB 基础(六)安全性(权限操作)
- 网站CDN监测接口