您好,登錄后才能下訂單哦!
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循環果然超時。
躺在床上想,會不會是雙指針問題。第二天做完提交,是的,典型的雙指針問題。啊哈哈,終于學到了。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。