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].
Because nums[ 0] + nums[ 1] = 2 + 7 = 9,
return [ 0, 1].
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int index1, index2;
int flag=0;
for(int i=0;i<numsSize;i++)
{
for(int j=0;j<numsSize;j++)
{
if(nums[i]+nums[j]==target&& i!=j)
{
index1=i;
index2=j;
flag=1;
break;
}
}
if(flag==1)
break;
}
printf("[%d,%d]",index1,index2);
int *indices =(int *)malloc(sizeof(int)*2);
indices[0] = index1;
indices[1] = index2;
return indices; //返回的是指针
}
int main()
{
int nums[] = {2,7,11,15};
int *p = twoSum(nums, 4, 9);
free(p);
}
- C/C++不支持返回数组?怎么办?
- 如何跳出双重for循环,注意使用flag
- 创建数组的一种方法:声明一个指针,调用malloc(),然后用该指针来访问数组元素。