LeetCode167. Two Sum II - Input array is sorted C语言
Givenanarrayofintegersthatisalreadysortedinascendingorder,findtwonumberssuchthattheyadduptoaspecifictargetnumber.ThefunctiontwoSumshouldreturnindicesofthetwonumberssuchthattheyadduptothetarget,whereindex1mustbelessthanindex2.Pleasenotethatyourreturnedanswers(bothindex1andindex2)arenotzero-based.Youmayassumethateachinputwouldhaveexactlyonesolution.Input:numbers={2,7,11,15},target=9Output:index1=1,index2=2
题意:一个排好序的数组,升序。给你一个数,从数组中找到和为这个数的俩索引,索引不是从0开始的。。。。。。且只有一组答案
/***Returnanarrayofsize*returnSize.*Note:Thereturnedarraymustbemalloced,assumecallercallsfree().*/int*twoSum(int*numbers,intnumbersSize,inttarget,int*returnSize){//复杂度不行啊!//inti,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;//returna;inti=0;intj=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;returna;}
PS:俩for循环果然超时。
躺在床上想,会不会是双指针问题。第二天做完提交,是的,典型的双指针问题。啊哈哈,终于学到了。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。