您的位置:首页 > 其它

LeetCode Problem:Two Sum

2015-09-03 19:30 323 查看
Problem 1:Two Sum

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

解题思路:

1.采用暴力方法,枚举所有组合,时间复杂度需要O(n*n)肯定会超时,事实也证明这种方法明显不行。

2.既然O(n*n)不行,那么就看能不能O(n*log n)了。要先弄清楚为什么1那种方法时间复杂度为什么会那么高,原因是它枚举了n*(n-1)/2对组合,而 里面其实有一大堆是没用的,比如target为10,给定的数组是[1,20,23,50,4,9],

那么涉及到20,23,50这些数的组合其实是不用去考虑的。现在问题是怎么避免去枚举那些没用的组合,一般到这里都会想到先排序,就可以把那些比较大的数归在一起了,而且注意到快速排序的时间复杂度为O(n*log n)

3.经过第二步的分析,那么我们就先排序,此时数组就是升序数组了,在升序数组找两个数的和为指定的值,时间复杂度可以降到O(n)。方法是弄两个指针i,j。开始是i执行数组第一个元素,j执行数组最后那个元素。然后开始循环,

如果nums[i]+nums[j]<target,那么i++,让总和增大,如果nums[i]+nums[j]>target,那么j--,让总和减小,如果nums[i]+nums[j]==target,那就说明我们找到了。

注意循环结束条件为i<j,不过题目说了一定有且仅有一个解,所以nums[i]+nums[j]==target一定会发生,在这里终止就行。

4.注意一点得到的结果数组下标要从1开始,而且小下标在前面。不过这是我们发现,题目要的是元素的数组下标,比如给个数组[4,2,5],4的下标为1,我们排序后数组为[2,4,5],4的下标为2,当然题目要的是1而不是2,但这是我们不知道4在原来数组的位置了。解决方法有多种,我采用的重新复制一个数组,这个数组的每个元素类型为Node类型,既保存了数值,有保存了该数值在原来数组的下标,这样排完序后我们就知道了这个数组在原来数组的下标了。

5时间复杂度快速排序为O(n*log n),查找用了O(n),因此整个程序的时间复杂度为O(n*log n)。

参考代码:

struct Node

{

int value;

int index;

};

bool cmp(const Node &m, const Node &n)

{

if(m.value <= n.value) return true;

return false;

}



class Solution {

public:

vector<int> twoSum(vector<int>& nums, int target) {

vector<Node> vec;

int i,j,n = nums.size();

Node node;

for(i=0;i<n;i++)

{

node.index = i;

node.value = nums[i];

vec.push_back(node);

}



sort(vec.begin(), vec.end(), cmp);

int temp;

i = 0;

j = vec.size() - 1;

while(i < j)

{

temp = vec[i].value + vec[j].value;

if(temp < target)

i++;

else if(temp > target)

j--;

else

{

vector<int> result;

int low = vec[i].index+1;

int high = vec[j].index+1;

if(low > high)

{

temp = low;

low = high;

high = temp;

}

result.push_back(low);

result.push_back(high);

return result;

}

}

}

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