溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2020-06-28 22:43:07 來源:網(wǎng)絡(luò) 閱讀:1573 作者:努力的C 欄目:編程語言
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

題意:一個排好序的數(shù)組,升序。給你一個數(shù),從數(shù)組中找到和為這個數(shù)的倆索引,索引不是從0開始的。。。。。。且只有一組答案

/**
 * 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) {
    //復(fù)雜度不行??!
    // 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循環(huán)果然超時。

躺在床上想,會不會是雙指針問題。第二天做完提交,是的,典型的雙指針問題。啊哈哈,終于學(xué)到了。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI