https://leetcode-cn.com/problems/two-sum/
给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
暴力法:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) //返回int型指针
{
int i,j;
int diff;
static int index[2]={0}; //加修饰符static,保证函数运行结束后,数组依然存在。
//int *index = (int *)malloc(sizeof(int)*2); //也可以用malloc
for(i=0;i<numsSize;i++)
{
diff = target - nums[i]; //对于每个差值,遍历数组,寻找是否存在
for(j=0;j<numsSize;j++)
{
if(diff == nums[j] && j!=i)
{
index[0] = i;
index[1] = j;
return index; //返回数组
}
}
}
return NULL;
}
//244ms 时间复杂度O(n^2) 空间复杂度O(1)
优化代码:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
static int index[2]={0};
int *p = malloc(sizeof(int)*numsSize); //申请一个数组保存所有差值。
for(int i = 0;i<numsSize;i++){ //对于第i个数,遍历下标
p[i] = target - nums[i]; //0到i-1的元素
for(int j = 0;j < i;j++){
if(nums[i] == p[j]){
index[0] = i;
index[1] = j;
free(p);
return index;
}
}
}
free(p);
return 0;
}
//84ms 时间复杂度O(n^2) 空间复杂度O(n)