题目:
1.Two Sum
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.
解题思路:一般做法是数组中第一个元素逐次和其之后的元素相加,并逐次检查其和是否等于目标值,若有符合要求的,则返回这两个元素的下标并结束程序,若无符合要求的,则用第二个元素,逐次和其之后的元素相加,并逐次检查其和是否等于目标值,若有符合要求的,则返回这两个元素的下标并结束程序。。。。如此重复,若无符合条件的则返回NULL;而本人的方法是前后同步进行相加并检查,代码如下:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int* ans=NULL;
int inv_i, inv_j;
ans = (int *)malloc(2*sizeof(int));
for(int i = 0; i < numsSize; ++i)
{
for(int j = i+1; j < numsSize; ++j)
{
if (nums[i] + nums[j] == target)
{
ans[0] = i, ans[1] = j;
return ans;
}
inv_i = numsSize - i - 1;
inv_j = numsSize - j + i;
if (nums[inv_i] + nums[inv_j] == target)
{
ans[0] = inv_j, ans[1] = inv_i;
return ans;
}
}
}
return ans;
}