LeetCode167 Two Sum II Input array is sorted

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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. Please note that 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.

样例

1
2
3
4
Input: 
numbers={2, 7, 11, 15}, target=9
Output:
index1=1, index2=2

思路

给一个递增的数组,从中找到两个元素使得它们的和等于给定的目标。

题目保证存在唯一解,并且同一个元素不能使用两次。

暴力的做法是枚举两个元素,复杂度$\mathcal{O}(n^2)$。

由于数组单调递增,可以枚举一个元素,然后二分搜索另外一个元素,复杂度$\mathcal{O}(logn)$。

再来考虑双指针的做法,$l$指向第一个元素,$r$指向第二个元素,由于数组有序,因此可以根据nums[l] + nums[r]target的大小关系来更新$l$或$r$。

代码

二分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
// 标准的二分查找
int find(vector<int>& nums, int key) {
int l = 0, r = nums.size() - 1;
while (l < r) {
int m = l + (r - l) / 2;
if (nums[m] < key) l = m + 1;
else r = m;
}
if (nums[r] == key) return r;
return -1;
}
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size();
vector<int> ans;
for (int i = 0; i < n; ++i) {
int j = find(numbers, target - numbers[i]);
if (i != j && j != -1) {
ans.push_back(min(i, j) + 1);
ans.push_back(max(i, j) + 1);
break;
}
}
return ans;
}
};

双指针

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int l = 0, r = numbers.size() - 1;
while (numbers[l] + numbers[r] != target) {
if (numbers[l] + numbers[r] < target) l++;
else r--;
}
//vector构造函数之一:通过list构造
return vector<int>({l + 1, r + 1});
}
};
分享到 评论