您的位置:首页 > 其它

LeetCode----Two Sum

2015-03-09 21:52 253 查看


Two Sum

Total Accepted: 69182 Total
Submissions: 382018My Submissions

Question
Solution

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

这道题网上有很多解法,好多都是使用map或者hash来解的,效率相对也比较高。但本题不能用两个循环来解决,

因为会超时,因此我们需要对算法进行优化。

我的思路如下,先用一个临时数组(temp)存储原数组的数据,然后对其进行排序,再设置两个指针left和

right,分别指向排序后数组的头和尾,利用二分查找的思想,如果temp[left] + temp[right] == target,已找到(唯一),

退出循环。否则,如果temp[left] + temp[right] > target,将right-1,否则left+1,基于这种二分的思想,最终会找到

满足条件的两个数,他们分别是temp[left]和temp[right],下面只要在原数组numbers中在找到这两个数的下标即可,

注意下标要从1开始,同时要注意有相等数字的出现,处理的办法是一个从前往后查找,一个从后往前查找,最后要

注意下两个下标需从小到大。代码如下:

int cmp(const void *a,const void *b)
{
return *(int *)a - *(int *)b;
}

int *twoSum(int numbers[], int n, int target)
{
int * ans = (int *)malloc(sizeof(int)*2);

int temp
;
int i;
for(i = 0;i<n;++i)
temp[i] = numbers[i];
qsort(temp,n,sizeof(int),cmp);

int left = 0;
int right = n-1;

while(left < right)
{
if(temp[left] + temp[right] == target)
break;
else if(temp[left] + temp[right] > target)
right--;
else
left++;
}
for(i = 0;i<n;++i)
{
if(numbers[i] == temp[left])
{
ans[0] = i+1;
break;
}
}
for(i = n-1;i>=0;--i)
{
if(numbers[i] == temp[right])
{
ans[1] = i+1;
break;
}

}
if(ans[0] > ans[1])
{
int t = ans[0];
ans[0] = ans[1];
ans[1] = t;
}
return ans;

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