当前位置:网站首页>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
- torch.optim.Adam() 函数用法
- swagger使用教程——快速使用swagger
- MySQL超详细安装教程 手把手教你安装MySQL到使用MySQL 最简单的MySQL安装方式,这种方式装,卸载也简单
- 服务器装好系统的电脑怎么分区
- LeetCode167:有序数组两数之和
- Chapter 6: Decisive Autumn Moves
- arcpy tutorial
- DTSE Tech Talk丨第2期:1小时深度解读SaaS应用系统设计
- 23. 请你谈谈关于IO同步、异步、阻塞、非阻塞的区别
猜你喜欢
随机推荐
data storage
LeetCode318:单词长度的最大乘积
[HarekazeCTF2019]Avatar Uploader 1
从零开始的Multi-armed Bandit
Deep Feedback Network for Recommendation
leetcode:1488. 避免洪水泛滥【二分 + 贪心】
DTSE Tech Talk丨第2期:1小时深度解读SaaS应用系统设计
测试管理与规范
Lotus 1.16.0 minimum snapshot export import
[极客大挑战 2020]Roamphp1-Welcome
升级Win11后不喜欢怎么退回Win10系统?
How does the new retail saas applet explore the way to break the digital store?
04、Activity的基本使用
onenote使用
[TypeScript] Introduction, Development Environment Construction, Basic Types
Public Key Retrieval is not allowed报错解决方案
华为云数据治理生产线DataArts,让“数据‘慧’说话”
UI测试新方法:视觉感知测试详解
23. 请你谈谈关于IO同步、异步、阻塞、非阻塞的区别
vivo announced to extend the product warranty period, the system launched a variety of functional services









