您的位置:首页 > 其它

LeetCode Two Sum

2016-11-21 20:57 429 查看

Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

1、快速排序

由于所给了array不是有序的,所以循环相加,时间会是O(m2), 这显然符合要求,所以可以先对array进行排序,快速排序的时间复杂度是 O(mlog(m)),明显复杂度要降低不少。但是题目要求得到的是原array的下标,所以在进行快速排序的时候需要同时对下标进行移位。这只需要在在快排函数中加入一个下标array,并且随元素进行移位

排序代码 :

void quick_sort(vector<int>&s, int l, int h,vector<int>&index)  {

if (l < h)
{ int i = l, j
4000
= h, x = s[l],key=index[l];
while (i < j)
{
while(i < j && s[j] >= x)
j--;
if(i < j)
{
index[i]=index[j];
s[i++] = s[j];
}

while(i < j && s[i] < x)
i++;
if(i < j)   {
index[j]=index[i];
s[j--] = s[i]; }
}
s[i] = x;
index[i]=key;
quick_sort(s, l, i - 1,index); // 递归调用
quick_sort(s, i + 1, h,index);
}
}


2、寻找符合条件的下标

在排序后,对有序array从左右两边进行循环判断是否符合,时间复杂度是O(m),一直把所有可能的组合进行遍历输出结果

代码如下:

while(i < j){
int x = nums[i] + nums[j];
if(x == target){
r.push_back(index[i]);
r.push_back(index[j]);
i++; j--;
}else if(x > target) j--;
else i++;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: