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

本文介绍了一种解决有序数组中寻找两个数使其和等于特定目标值的问题的方法。使用双指针技巧,从数组两端开始向中间搜索,有效提高了查找效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值