您的位置:首页 > 其它

LeetCode | 1.Two Sum

2016-05-21 16:06 344 查看

LeetCode|1.Two Sum

Give an array of integers,find two numbers such that they add up to a specific target number.

You may assume that each input would have exactly one solution.

Example:

Input: numbers={2, 7, 11, 15}, target=9

output: index1=1, index2=2

编程思路:

题目的要求是给定一组数,从中找到和为一个给定值的两个数,并返回它们的下标。即找到a和b满足a+b=target。

思路一:

遍历数组中的某一个数,在遍历其之后的所有数,计算并找到满足要求的两个数,结束遍历返回下标。时间复杂路为O(N(N -1)),即O(N^2)。空间复杂度为O(1)。

代码: (C)

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int i, j;
int flag=0;
int *ans;
ans = (int*)malloc(sizeof(int)*2);
ans[0]=ans[1]=-1;
for(i=0;i<numsSize-1;i++){
for(j=i+1;j<numsSize;j++){
if(target==nums[i]+nums[j]){
ans[0]=i;
ans[1]=j;
flag=1;
break;
}
}
if(flag==1)
break;
}
if(flag==1)
return ans;
else
return 0;
}

思路二:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: