来源:力扣(LeetCode)
链接:力扣
题目描述:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
最简单的想法是先选定一个数,再从数组里查找是否存在另一个数使得这两个数的和等于 target,直接暴力搜索。
时间复杂度:O()
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
*returnSize=2;//保证一定存在解,因此直接将返回数组的大小设定为2
int *ans=(int*)malloc(sizeof(int)*2);//题目要求返回一个数组
for(int i=0;i<numsSize;++i)//选定第一个数
for(int j=i+1;j<numsSize;++j)//选定第二个数
if(nums[i]+nums[j]==target)
{
ans[0]=i,ans[1]=j;break;
}
return ans;
}
进阶要求:时间复杂度小于O()
如果查找的数组是有序的,可以在数组的开头和结尾分别设置两个标志,开头标志为head,结尾标志为tail。令 temp=num[head]+num][tail] ,则 temp 的值与 target 可能有3种情况:
1、temp=target 此时的 head 和 tail 即为所求。
2、temp<target 因为数组有序,想要让两数之和 temp 增大,只需要将 head 向后移一位,再进行比较。
3、temp>target 与第二种情况类似,此时只需要将 tail 向前移一位,再进行比较。
整个过程只对数组 nums 进行了一次遍历,时间复杂度为 O() 。注意题目给出的数组是无序的,需要对数组先进行排序。在排序的时候,因为要求返回的是两个数据的下标,所以要先记录下每个数据在原数组的位置,再排序。如使用快速排序、归并排序等方法,排序的时间复杂度为 O() 。总的时间复杂度为 O()。
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
struct num{
int value;
int subscript;
};//由于要返回的是两个数在原数组的下标,为避免丢失下标信息,使用结构体
int cmp(const void *a ,const void *b) //快速排序的比较函数
{
struct num *c=(struct num*)a;
struct num *d=(struct num*)b;
return c->value-d->value;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
*returnSize=2;
int *ans=(int*)malloc(sizeof(int)*2);
struct num *n=(struct num*)malloc(sizeof(struct num)*numsSize);
for(int i=0;i<numsSize;++i)//对数组元素进行复制,并记录对应下标
n[i].value=nums[i],n[i].subscript=i;
qsort(n,numsSize,sizeof(struct num),cmp);//快速排序
int head=0,tail=numsSize-1;//头尾标志
while(n[head].value+n[tail].value!=target)//进行查找
{
if(n[head].value+n[tail].value>target)tail--;
else if(n[head].value+n[tail].value<target)head++;
}
ans[0]=n[head].subscript,ans[1]=n[tail].subscript;
free(n);
return ans;
}