Description:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
给定一个整形数组,找出两个数的总和等于一个特定的目标,返回这两个数字的索引。
可以假设每个输入都有一个解决方案,并且可能不会使用相同的元素两次。
暴力解法O(n^2)
用双层for循环,,对于数组a中的每一个数据a[i]判断后面是否有某个数a[j],使得a[i]+a[j]=target;
int* twoSum(int* nums, int numsSize, int target) {
int *a=(int *)malloc(sizeof(int)*2);
int i,j;
for(i=0;i<numsSize;i++)
{
for(j=i+1;j<numsSize;j++) //不能用j<=numSize
{
if(nums[i]+nums[j]==target)
{
a[0]=i;
a[1]=j;
return a;
}
}
}
return NULL;
}
注意 j<numSize 不能有等于,倘若有的话会出现:
如上,最后两个数据就会出问题
进阶解法:使用Hash表
cpp中的STL容器封装了Hash的实现,使用cpp的话可以减少代码量的同时减少时间复杂度到O(n)
但由于我现在还没有学cpp,Hash表的实现也不熟,过段时间来更新该解法...
......