可以先看下 超详细讲解:leetcode-leetcode-0001-TwoSum(两数之和),这个是其第二个版本,即增加了数组是有序数组这一条件。难度:简单。
1. 题目地址
2. 题目描述
- 英文描述
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 1:
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.
Example 2:
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Example 3:
Input: numbers = [-1,0], target = -1
Output: [1,2]
Constraints:
2 <= nums.length <= 3 * 104
-1000 <= nums[i] <= 1000
nums is sorted in increasing order.
-1000 <= target <= 1000
- 中文描述
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
3. 解题思路
- 方法1:hash表
- 首先, 超详细讲解:leetcode-leetcode-0001-TwoSum(两数之和) 这个题目中的所有方法对本题都是适用的。
- 以一次遍历的方法再介绍一遍,即遍历的时候一边存表一边查表。
- 将求和的问题转化为求差值的方法来解决,即:nums[j] = target - nums[i]。
- 遍历数组中的元素,查询表中是否已经存在当前元素所对应的目标元素 (target-nums[i]),如果存在,那么就已经找到了对应解,立即返回结果,不再往后执行了。如果不存在,那就进行存表的步骤,继续往下遍历查找,直到查询到目标值。
- 时间复杂度:O(n)
- 空间复杂度:O(n)
- 最优解法:双指针
- 这道题很有利的利用条件就是:输入为有序数组。数组是有序数组,所以可以省略排序的过程,直接用双指针进行判断。而且如果题目对空间复杂度有要求,用双指针的解法就是最佳解法,空间复杂度为O(1)。
- 首先指定一个 left 指针,一个 right 指针,分别指在数组的头和尾。
- 如果 left + right 的值 > target,则 right 指针向左移动, 否则 left 指针向右移动,直到 left + right = target。
- 时间复杂度:O(n)
- 空间复杂度:O(1)
4. 解题关键
- 要想到要想到双指针的操作
- 第1步:两个指针,一个指向数组头,一个指向数组尾。
- 第2步:如果 left + right 的值 > target,则 right 指针向左移动, 否则 left 指针向右移动。
- 第3步:直到 left + right = target,返回 left 和 right 。
- 要点
- 返回的下标值(index1 和 index2)不是从零开始的,所以最后的 index 要 +1。
- 复杂度
- 时间复杂度:O(n)
- 空间复杂度:O(1)
5. 示例代码
python
# -*- coding:utf-8 -*-
'''
# @Method:双指针
# @Author: wlhr62
'''
import time
class Solution:
def twoSum(self, numbers, target):
if numbers is not None:
left = 0
right = len(numbers) - 1
while numbers[left] + numbers[right] != target and left < right:
if numbers[left] + numbers[right] > target:
right-=1
else:
left+=1
return [left+1, right+1]
else:
return None
if __name__ == '__main__':
numbers = [2, 7, 11, 15]
target = 9
A = Solution()
res = A.twoSum(numbers, target)
print(res)
运行结果
[1, 2]