LeetCode(C语言) - 167. 两数之和 II - 输入有序数组
https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/
注意
参数returnSize为址传递,应赋值为2,表示返回的数组长度为2
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
}
提交代码1:暴力法
时间复杂度为O(\(n^2\))
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
*returnSize=2;
int *res=(int *)malloc(2*sizeof(int));
for(int i=0;i<numbersSize-1;i++){
for(int j=i+1;j<numbersSize;j++){
if(numbers[i]+numbers[j] == target){
res[0] = i+1;
res[1] = j+1;
return res;
}
}
}
res[0] = 1;
res[1] = 2;
return res;
}
执行结果
执行结果:
通过
显示详情
添加备注
执行用时:
1184 ms
, 在所有 C 提交中击败了
9.19%
的用户
内存消耗:
7.1 MB
, 在所有 C 提交中击败了
56.87%
的用户
通过测试用例:
21 / 21
完整代码
#include <stdio.h>
#include <malloc.h>
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
*returnSize=2;
int *res=(int *)malloc(2*sizeof(int));
for(int i=0;i<numbersSize-1;i++){
for(int j=i+1;j<numbersSize;j++){
if(numbers[i]+numbers[j] == target){
res[0] = i+1;
res[1] = j+1;
return res;
}
}
}
res[0] = 1;
res[1] = 2;
return res;
}
main(){
// int a[] = {2,7,11,15},target = 9;
int a[] = {2,3,4},target = 6;
int len = sizeof (a) / sizeof (int);
for(int i=0;i<len;i++){
printf("%d ",a[i]);
}
printf("\n");
int returnSize;
int* b = twoSum(a,len,target,&returnSize);
for(int i=0;i<returnSize;i++){
printf("%d ",b[i]);
}
printf("\n");
}
控制台输出
2 3 4
1 3
--------------------------------
Process exited after 0.3133 seconds with return value 0
请按任意键继续. . .
思路2 : 二分法
时间复杂度O(nlogn)
第一层i和代码1一样,第二层通过二分法查找target-numbers[i],查找到返回i和值为target-numbers[i]的下标,找不到i+1继续。
二分法依赖数组的有序性。
代码暂时先不实现了
思路3 : 对撞指针
时间复杂度O(n)
两头往中间挤,从而找到两个目标元素的下标。依赖数组的有序性。
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
*returnSize=2;
int *res=(int *)malloc(2*sizeof(int));
int left=0,right=numbersSize-1;
while(left<right){
if(numbers[left]+numbers[right]<target){
left++;
}else if(numbers[left]+numbers[right]>target){
right--;
}else{
break;
}
}
res[0] = left+1;
res[1] = right+1;
return res;
}
执行结果
执行结果:
通过
显示详情
添加备注
执行用时:
12 ms
, 在所有 C 提交中击败了
91.06%
的用户
内存消耗:
7 MB
, 在所有 C 提交中击败了
58.90%
的用户
通过测试用例:
21 / 21