当前位置:网站首页>【leetcode】剑指 Offer II 006. 排序数组中两个数字之和(二分查找、双指针)
【leetcode】剑指 Offer II 006. 排序数组中两个数字之和(二分查找、双指针)
2022-07-29 22:46:00 【friedrichor】
剑指 Offer II 006. 排序数组中两个数字之和
问题描述
给定一个已按照 升序排列 的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。
函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 0 开始计数 ,所以答案数组应当满足 0 < = a n s w e r [ 0 ] < a n s w e r [ 1 ] < n u m b e r s . l e n g t h 0 <= answer[0] < answer[1] < numbers.length 0<=answer[0]<answer[1]<numbers.length 。
假设数组中存在且只存在一对符合条件的数字,同时一个数字不能使用两次。
示例 1:
输入:numbers = [1,2,4,6,10], target = 8
输出:[1,3]
解释:2 与 6 之和等于目标数 8 。因此 index1 = 1, index2 = 3 。
示例 2:
输入:numbers = [2,3,4], target = 6
输出:[0,2]
示例 3:
输入:numbers = [-1,0], target = -1
输出:[0,1]
提示:
- 2 <= numbers.length <= 3 * 1 0 4 10^4 104
- -1000 <= numbers[i] <= 1000
- numbers 按 递增顺序 排列
- -1000 <= target <= 1000
- 仅存在一个有效答案
思路&代码
方法一:穷举
略
方法二:二分法
二分查找相关讲解:【二分查找】详细图解
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
length = len(numbers)
for i in range(length - 1):
low = i + 1
high = length - 1
while low <= high:
mid = (low + high) // 2
if numbers[mid] == target - numbers[i]:
return [i, mid]
elif numbers[mid] > target - numbers[i]:
high = mid - 1
else:
low = mid + 1
时间复杂度: O ( n log n ) O(n \log n) O(nlogn),其中 n 是数组的长度。需要遍历数组一次确定第一个数,时间复杂度是 O ( n ) O(n) O(n),寻找第二个数使用二分查找,时间复杂度是 O ( log n ) O(\log n) O(logn),因此总时间复杂度是 O ( n log n ) O(n \log n) O(nlogn)。
空间复杂度: O ( 1 ) O(1) O(1)。
方法三:双指针
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
low = 0
high = len(numbers) - 1
while low < high:
sum = numbers[low] + numbers[high]
if sum == target:
return [low, high]
elif sum > target:
high -= 1
else:
low += 1
时间复杂度: O ( n ) O(n) O(n),其中 n n n 是数组的长度。两个指针移动的总次数最多为 n n n 次。
空间复杂度: O ( 1 ) O(1) O(1)。
边栏推荐
猜你喜欢

C语言快速入门(为了看源码)

PyCharm使用教程(详细版 - 图文结合)

使用 Neuron 接入 Modbus TCP 及 Modbus RTU 协议设备

J9 Number Theory: Why do we need Web3?

我想申请专利,却没有经验,如何学会写专利申请文件?

高等数学(第七版)同济大学 习题3-7 个人解答

嵌入式系统驱动初级【1】——内核模块上_编译方法

This article penetrates the architecture design and cluster construction of the distributed storage system Ceph (hands-on)

研究生怎么申请专利,流程是什么?

不要再用if-else!
随机推荐
SQL 改写系列七:谓词移动
Professor Lu Shouqun from COPU was invited to give a speech at ApacheCon Asia
The sequence table of the linear table (the dry goods are full of sharing ~ contains all the function codes of the sequence table~
JZ22 链表中倒数最后k个结点
一文参透分布式存储系统Ceph的架构设计、集群搭建(手把手)
【企业架构】描绘未来第 3 部分:产品路线图
聊聊阻容降压原理 和 实际使用的电路
撰写英文文献有哪些技巧?
8万字带你入门Rust
cached_network_image 多个图片卡顿崩溃
JetsonNano学习(六)Jetson踩过的大坑及解决方法___持续更新
leetcode 890. Find and Replace Pattern(查找和替换pattern)
Cloud computing 1+X openstack articles
把字符串转换成整数
【R语言】【2】绘图base和lattice和ggplot2库
二、HikariCP源码分析之获取连接流程二
This article penetrates the architecture design and cluster construction of the distributed storage system Ceph (hands-on)
新型LaaS协议Elephant Swap给ePLATO提供可持续溢价空间
rtsp-simple-server + srs搭建流媒体服务器
JZ24 反转链表