LeetCode Two Sum II Input array is sorted

Description

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.

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

The original problem is here.

My Solution

I solve this problem in C++, as below:

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
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res;
int index = -1;
for (int i = 0; i < numbers.size(); i++) {
index = findIndex(numbers, i+1, numbers.size()-1, target-numbers[i]);
if (index != -1) {
res.push_back(i+1);
res.push_back(index+1);
return res;
}
}
return res;
}
int findIndex(vector<int>& nums, int i, int j, int target) {
if (i>j)
return -1;
if(i==j) {
if(nums[i] != target)
return -1;
else
return i;
}
int index;
while (i <= j) {
index = (i+j)/2;
if(nums[index] == target) {
return index;
} else if (nums[index] < target) {
i = index + 1;
} else {
j = index - 1;
}
}
return -1;
}
};

Note

To solve the problem, traverse the array and find the number which add by the current element is equal to target.
Use binary search when find the other number by the array is sorted.


LeetCode Two Sum II Input array is sorted
http://zhaoshuaijiang.com/2017/01/19/leetcode-Two-Sum-II-Input-array-is-sorted/
作者
shuaijiang
发布于
2017年1月19日
许可协议