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

相关文章
|
算法 C语言
【C语言】Leetcode 27.移除元素
【C语言】Leetcode 27.移除元素
【C语言】Leetcode 27.移除元素
|
C语言
【Leetcode-1.两数之和 -3.无重复字符的最长子串 -9.回文数(C语言)】
【Leetcode-1.两数之和 -3.无重复字符的最长子串 -9.回文数(C语言)】
269 0
|
存储 C语言
Leetcode—— 删除排序数组中的重复项——C语言
Leetcode—— 删除排序数组中的重复项——C语言
393 0
|
算法 C语言
Leetcode----旋转数组 ------C语言篇
Leetcode----旋转数组 ------C语言篇
265 0
|
C语言
LeetCode---消失的数字---C语言实现
LeetCode---消失的数字---C语言实现
207 0
|
程序员 C语言
【C语言】LeetCode(力扣)上经典题目
【C语言】LeetCode(力扣)上经典题目
485 1
|
存储 算法 C语言
C语言刷题~Leetcode与牛客网简单题
C语言刷题~Leetcode与牛客网简单题
|
存储 C语言
【C语言】Leetcode 88.合并两个有序数组
【C语言】Leetcode 88.合并两个有序数组
|
存储 搜索推荐 C语言
Leetcode—合并两个有序数组—C语言
Leetcode—合并两个有序数组—C语言
280 0
|
机器学习/深度学习 canal NoSQL
从C语言到C++_12(string相关OJ题)(leetcode力扣)
从C语言到C++_12(string相关OJ题)(leetcode力扣)
309 0