求数组中任意两个数相加的算法


#include <stdio.h>
#include <string.h>
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
   
    int *p = (int *)malloc(2*sizeof(int));
    int i,j;
    int ret =0;
    for(i =0 ;i< numsSize;i ++)
    { 
        for(j = i+1 ;j < numsSize  ;j++){
            if(nums[i] + nums[j] == target)
            {
                 *p = i;
                 *(p+1)=j;
                 ret +=2;
            }
        }
    }
    *returnSize = ret;
	 
    return p;
    free(p);
}
int main()
{
   int sizt;
   int n[]={3,2,4};
   int *p =twoSum(n,3,6, &sizt);
   printf("%d %d %d \n",*p,*(p+1),sizt);
}

sitemap