[LC] 167. Two Sum II - Input array is sorted
2024-09-07 06:54:23
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.
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
my_dict = {}
for i, num in enumerate(numbers):
remain = target - num
if remain in my_dict:
index = my_dict[remain]
return [index, i + 1]
my_dict[num] = i + 1
return [-1, -1]
最新文章
- android基础(六)android的消息处理机制
- CPlus的简单线程的制作
- Linux第八次学习笔记
- 【IHttpHandler】使用IHttpHandler防盗链
- 最新 Arduino 驱动 12接口/户外 LED显示屏/LED点阵屏/LED单元板
- Java学习小结(1)-数组的创建与传参
- JavaScript基础-面向对象编程<;1>;
- WebLech是一个功能强大的Web站点下载与镜像工具
- CentOS7 已安装telnet维修
- openstack私有云布署实践【12.2 网络Neutron-controller节点配置(办公网环境)】
- 老李分享:Python开发性能测试脚本
- stick footer布局
- spring mvc报错,数据库查询无限死循环
- JVM-垃圾收集的过程
- TCP的三次握手过程与四次挥手
- 【MM系列】SAP的库存管理
- maven中jar下载失败
- npm 发布包(publish)
- numpy 数据处理
- artTemplate 原生 js 模板语法版