当前位置:网站首页>LeetCode167: Sum of two numbers in sorted array
LeetCode167: Sum of two numbers in sorted array
2022-07-30 16:55:00 【Daisy_D99】
难度:simple
本题同时也是《剑指offer 专项突击》的第6题【数组专题】.
problem
https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/
or
https://leetcode.cn/problems/kLl5u1/
给定一个已按照 升序排列 的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target .
函数应该以长度为 2 的整数数组的形式返回这两个数的下标值.numbers 的下标 从 0 开始计数 ,所以答案数组应当满足 0 <= answer[0] < answer[1] < numbers.length .
假设数组中存在且只存在一对符合条件的数字,同时一个数字不能使用两次.
类似的题
leetcode 1 号算法题:两数之和
leetcode 167 号算法题:两数之和Ⅱ - 输入有序数组
leetcode 170 号算法题:两数之和Ⅲ - 数据结构设计
leetcode 653 号算法题:两数之和Ⅳ - 输入 BST
leetcode 15 号算法题:三数之和
leetcode 18 号算法题:四数之和
哈希表
存 值-ID 对, save and find.
双指针
Double pointers for sorted arrays start at both ends.Move in the direction of the small,Move in the direction of the larger.
完整代码
class Solution:
def twoSum(self, numbers, target: int):
# hash 表: 值-ID
# dic ={}
# for i in range(len(numbers)):
# if target - numbers[i] in dic:
# return [dic[target-numbers[i]], i]
# dic[numbers[i]] = i
# 双指针
i = 0
j = len(numbers)-1
while i <= j:
if numbers[i]+numbers[j] == target:
return [i+1,j+1]
elif numbers[i]+ numbers[j]<target:
i +=1
else:
j-=1
边栏推荐
猜你喜欢
Scheduling_Channel_Access_Based_on_Target_Wake_Time_Mechanism_in_802.11ax_WLANs
Go新项目-编译热加载使用和对比,让开发更自由(3)
onenote use
每日一题:两数之和
Nervegrowold d2l (7) kaggle housing forecast model, numerical stability and the initialization and activation function
【SOC】Classic output hello world
[MRCTF2020]Ezaudit
升级Win11后不喜欢怎么退回Win10系统?
登录模块调试-软件调试入门
李沐d2l(七)kaggle房价预测+数值稳定性+模型初始化和激活函数
随机推荐
登录模块调试-软件调试入门
支付系统架构设计详解,精彩!
gvim命令记录
You are a first-class loser, you become a first-class winner
基于STM32F407使用ADC采集电压实验
CMake库搜索函数居然不搜索LD_LIBRARY_PATH
Deep Feedback Network for Recommendation
onenote use
Leetcode 119. Yang Hui's Triangle II
[TypeScript] Introduction, Development Environment Construction, Basic Types
mysql进制安装与mysql密码破解
DTSE Tech Talk丨第2期:1小时深度解读SaaS应用系统设计
华为云数据治理生产线DataArts,让“数据‘慧’说话”
The case of five little pigs (five little pigs compare the size of the body weight)
阿里巴巴中国站获得1688商品分类 API
MySQL 8.0.29 解压版安装教程(亲测有效)
torch.optim.Adam() function usage
牛客网刷题——运算符问题
win下搭建php环境的方法
深度学习区分不同种类的图片