溫馨提示×

溫馨提示×

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

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

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

發布時間:2020-06-28 22:43:07 來源:網絡 閱讀:1577 作者:努力的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

題意:一個排好序的數組,升序。給你一個數,從數組中找到和為這個數的倆索引,索引不是從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) {
    //復雜度不行??!
    // 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循環果然超時。

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

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女