【题目】
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
【答案】
/*************************************************************************
* 文件: add_two_num.c
* 作者: fantasy
* 邮箱: fantasy@gmail.com
* 创建时间: 2015年05月03日 星期日 21时42分32秒
*************************************************************************/
#include <stdio.h>
#include <stdlib.h>
int* twoSum(int* nums, int numsSize, int target)
{
int i, j;
int complete = 0;
int* index = NULL;
index = (int*)malloc(2 * sizeof(int));
index[0] = 0;
index[1] = 0;
if (NULL == index)
{
return NULL;
}
for (i = 0; i < numsSize - 1; i++)
{
for (j = i; j < numsSize; j++)
{
if ((nums[i] + nums[j]) == target)
{
index[0] = i + 1;
index[1] = j + 1;
complete = 1;
break;
}
}
if (1 == complete)
{
break;
}
}
return index;
}
int main()
{
int nums[] = {2, 7, 11, 15};
int target = 18;
int* index;
index = twoSum(nums, sizeof(nums)/sizeof(nums[0]), target);
if (index == NULL)
{
return -1;
}
else
{
printf("index0 = %d, index1 = %d\n", index[0], index[1]);
return 0;
}
}