Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

原题地址: Two Sum II - Input array is sorted

难度: Easy

思路1:

采用缓存的方式,用字典记录每一个值的索引

代码:

class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for idx, num in enumerate(numbers):
if target - num in d:
idx1 = d[target-num]
return [idx1+1, idx+1]
else:
d[num] = idx

时间复杂度: O(n)

空间复杂度: O(n)

思路2:

因为数组已经排序了,可以分别在数组首尾放置一指针,逐渐向中间夹逼

代码:

class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
i, j = 0, len(numbers)-1
while i < j:
val = numbers[i] + numbers[j]
if val == target:
return [i+1, j+1]
elif val > target:
j -= 1
else:
i += 1

时间复杂度: O(n)

空间复杂度: O(1)

最新文章

  1. python-socket模块
  2. 以最简单方式学习Linux
  3. django rest framework 再撸体验
  4. mysql悲观锁总结和实践--转
  5. eAccelerator、memcached、xcache、APC 等四个加速扩展的区别
  6. Sublime Text 3 配置Java开发
  7. ae开发基础功能
  8. NOJ1018-深度遍历二叉树
  9. CODE:BLOCK中的CreateProcess: No such file or directory
  10. linux为命令取别名
  11. Oracle 安装中遇到的问题
  12. 信息熵(Entropy)究竟是用来衡量什么的?
  13. Alice and Bob(mutiset容器)
  14. java(样品集成框架spring、spring mvc、spring data jpa、hibernate)
  15. Linux笔记(五) - 用户管理命令
  16. java构造器和构建器
  17. 根据txt中的文件名将文件复制到目标文件夹中
  18. 2-sat-总结+例题
  19. CentOS安装中文支持包
  20. Xilinx 7 series FPGA multiboot技术的使用(转)

热门文章

  1. 进击python第三篇:基础
  2. tree(2018.10.26)
  3. window git bash客户端vimrc设置tab缩进
  4. [题解](单调队列)luogu_P2216_BZOJ_1047 理想的正方形
  5. 2017 Multi-University Training Contest - Team 1 KazaQ&#39;s Socks
  6. jQuery addClass() 源码解读
  7. Vue实例的4个常用选项
  8. IE兼容只读模式
  9. Android 两个ArrayList找出相同元素及单个ArrayList删除元素
  10. TFS数据库分离附加经验总结