167. Two Sum II - Input array is sorted@python
2024-09-03 18:20:27
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)
最新文章
- python-socket模块
- 以最简单方式学习Linux
- django rest framework 再撸体验
- mysql悲观锁总结和实践--转
- eAccelerator、memcached、xcache、APC 等四个加速扩展的区别
- Sublime Text 3 配置Java开发
- ae开发基础功能
- NOJ1018-深度遍历二叉树
- CODE:BLOCK中的CreateProcess: No such file or directory
- linux为命令取别名
- Oracle 安装中遇到的问题
- 信息熵(Entropy)究竟是用来衡量什么的?
- Alice and Bob(mutiset容器)
- java(样品集成框架spring、spring mvc、spring data jpa、hibernate)
- Linux笔记(五) - 用户管理命令
- java构造器和构建器
- 根据txt中的文件名将文件复制到目标文件夹中
- 2-sat-总结+例题
- CentOS安装中文支持包
- Xilinx 7 series FPGA multiboot技术的使用(转)
热门文章
- 进击python第三篇:基础
- tree(2018.10.26)
- window git bash客户端vimrc设置tab缩进
- [题解](单调队列)luogu_P2216_BZOJ_1047 理想的正方形
- 2017 Multi-University Training Contest - Team 1 KazaQ&#39;s Socks
- jQuery addClass() 源码解读
- Vue实例的4个常用选项
- IE兼容只读模式
- Android 两个ArrayList找出相同元素及单个ArrayList删除元素
- TFS数据库分离附加经验总结