题目
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
解答方法一:双重循环尝试, 复杂度O(n^2)
#include<stdio.h>
#include<stdlib.h>
int *twoSum(int numbers[], int n, int target)
{
if ((numbers == NULL)|(n < 2))
{
return NULL;
}
int index1;
int index2;
int* ret = (int*)malloc(sizeof(int)*2);
for (index1 = 0; index1 < n; ++index1)
{
for (index2 = index1 + 1; index2 < n; ++index2)
{
int sum_tmp = numbers[index1] + numbers[index2];
if (sum_tmp == target)
{
ret[0] = index1 + 1;
ret[1] = index2 + 1;
return ret;
}
}
}
return NULL;
}
int main(int argc, char **argv)
{
int array[] = { 2, 7, 11, 15};
size_t n = sizeof(array)/sizeof(int);
int target = 9;
int* result = twoSum(array, (int)n, target);
printf("The index1: %d; the index2: %d\n", result[0], result[1]);
free(result);//memory deallocation
}
点评:
解法非常直观, 但是复杂度O(n^2),所以效率很差,在leetcode上无法通过: Submission Result: