题目描述 LeetCode 167
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:
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.
题目解读
- 从一个数组中找到两个数,使这两个数相加等于给定的target,输出数组中这两个数的下标(下标从1开始)
解题思路
- 题目中规定,第一个数的下标小于第二个;所以依次遍历数组,如取出第
i
个数字,则将i
后面的数字作为一个新的数组放入二分查找中进行搜索,搜索目标为 target - number[i], 如果找到则返回下标,循环终止;找不到则返回-1,开始下一次循环
Code
# include<stdio.h>
int BinarySearch(int rr[], int left, int right, int x){
int index = (right + left) / 2;
int mid = rr[index];
if(left <= right){
if(x < mid){
return BinarySearch(rr, left, index - 1, x);
}
else if(x > mid){
return BinarySearch(rr, index + 1, right, x);
}
else{
return index;
}
}
else{
return -1;
}
}
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
int i;
int index1, index2;
static int temp[2];
for (i = 0; i < numbersSize; i ++){
index1 = i;
index2 = BinarySearch(numbers, i + 1, numbersSize - 1, target - numbers[i]);
if (index2 > 0){
break;
}
}
temp[(*returnSize) ++ ] = index1 + 1;
temp[(*returnSize) ++ ] = index2 + 1;
return temp;
}
int main(){
int a[10] = {0, 0, 3, 4};
int target = 0;
int returnSize = 0;
int i;
int* temp;
temp = twoSum(a, 4, target, &returnSize);
for(i = 0; i < returnSize; i ++){
printf("%d ", temp[i]);
}
}
- 思路二 二分查找 C++ 实现
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> result;
for(int i=0; i < numbers.size() - 1; i++){
int tt = BinarySearch(numbers, i+1, numbers.size()-1, target-numbers[i]);
if(tt > 0){
result.push_back(i+1);
result.push_back(tt+1);
break;
}
}
return result;
}
int BinarySearch(vector<int>& nums, int left, int right, int target){
if(left <= right){
int indexOfmed = (left + right) / 2;
int med = nums[indexOfmed];
if(target < med){
return BinarySearch(nums, left, indexOfmed-1, target);
}
else if(target > med){
return BinarySearch(nums, indexOfmed+1, right, target);
}
else{
return indexOfmed;
}
}
else{
return -1;
}
}
};