Problem Description:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
这个题的大致意思就是输入一串数nums和目标数target,找出其中两个数和为目标数的下标,并返回。
这道题比较简单,一个遍历就能解决。有两种思路:1、直接找两个数判断和是否为目标数,两重循环,最坏情况复杂度O(N^2);2、用目标数减去其中一个数,再在数组中查找,最坏复杂度也是O(N*查找算法的复杂度)。如果用二分法查找,则为O(N*log(N));
再来看一下所给的函数接口:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
}
传递三个形参,数组首地址、数组大小、目标数。返回指针。从返回指针就可以知道,需要malloc,不然的话函数里面定义的数组会被直接释放,只有malloc开辟的内存是放在堆里面的,不会直接释放。
源代码:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int i,j,k=0;
int sum;
int t[numsSize],*s;
for(i = 0; i < numsSize; i++)
{
sum = nums[i];
for(j = i+1; j< numsSize; j++)
{
sum += nums[j];
if(sum == target) /* 若找到,则存储下标 */
{
t[k++] = i;
t[k++] = j;
}
sum = nums[i]; /* 重新赋初值 */
}
}
s = (int *)malloc(k*sizeof(int));
for(i = 0; i < k; i++)
s[i] = t[i];
return s;
}
运行结果:
我用的是第一种算法,从运行时间可以看出,这个算法一般;可以试着用第二种算法改进,鉴于目前时间关系以后有时间在编写。欢迎探讨,谢谢!