1
2
3
4
5
|
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
|
题意:一个排好序的数组,升序。给你一个数,从数组中找到和为这个数的俩索引,索引不是从0开始的。。。。。。且只有一组答案
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
|
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int
* twoSum(
int
* numbers,
int
numbersSize,
int
target,
int
* returnSize) {
//复杂度不行啊!
// int i,j;
// int *a=(int*)malloc(sizeof(int)*2);
// for(i=0;i<numbersSize;i++){
// for(j=i+1;j<numbersSize;j++){
// if(numbers[i]+numbers[j]==target){
// a[0]=i+1;
// a[1]=j+1;
// break;
// }
// }
// }
// *returnSize=2;
// return a;
int
i=0;
int
j=numbersSize-1;
int
*a=(
int
*)
malloc
(
sizeof
(
int
)*2);
while
(i<j){
if
(numbers[i]+numbers[j]==target){
a[0]=i+1;
a[1]=j+1;
break
;
}
if
(numbers[i]+numbers[j]>target){
j--;
}
if
(numbers[i]+numbers[j]<target){
i++;
}
}
*returnSize=2;
return
a;
}
|
PS:俩for循环果然超时。
躺在床上想,会不会是双指针问题。第二天做完提交,是的,典型的双指针问题。啊哈哈,终于学到了。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1867917