LeetCode167. Two Sum II - Input array is sorted C语言

简介:
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

相关文章
|
4月前
|
算法 C语言 容器
从C语言到C++_18(stack和queue的常用函数+相关练习)力扣(上)
从C语言到C++_18(stack和queue的常用函数+相关练习)力扣
38 0
|
4月前
|
存储 C语言
Leetcode—— 删除排序数组中的重复项——C语言
Leetcode—— 删除排序数组中的重复项——C语言
|
4月前
|
算法 C语言
Leetcode----旋转数组 ------C语言篇
Leetcode----旋转数组 ------C语言篇
|
4月前
|
C语言
LeetCode---消失的数字---C语言实现
LeetCode---消失的数字---C语言实现
|
4月前
|
算法 C语言 容器
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145(下)
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145
49 7
|
4月前
|
存储 算法 C语言
从C语言到C++_39(C++笔试面试题)next_permutation刷力扣
从C语言到C++_39(C++笔试面试题)next_permutation刷力扣
36 5
|
4月前
|
存储 C语言 容器
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(下)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
36 1
|
4月前
|
存储 C语言 容器
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(中)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
40 1
|
4月前
|
存储 自然语言处理 C语言
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(上)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
43 1
|
4月前
|
C语言
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145(中)
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145
41 1