首页 > 代码库 > Two Sum
Two Sum
link:https://oj.leetcode.com/problems/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
先排序O(NlogN),然后两个指针,一个在最前,一个在最后,开始扫描,两个值的和大于target,后面指针往前移动,两个值得和小于target,前面指针往后移动,若和等于target,则是解。
参考代码:
#include<iostream>
#include <vector>
#include <stdio.h>
usingnamespace std;
struct Node{
int val;
int index;
};
bool cmp(Node a,Node b)
{
return a.val<b.val;
}
vector<int> twoSum(vector<int> &numbers,int target)
{
vector<int> ret;
vector<Node> nodeArr;
for (int i=0; i<numbers.size(); i++) {
Node item;
item.val=numbers[i];
item.index=i+1;
nodeArr.push_back(item);
}
sort(nodeArr.begin(), nodeArr.end(),cmp);
int start=0;
int end=(int)numbers.size()-1;
while (start<nodeArr.size() && end>=0) {
if (nodeArr[start].val+nodeArr[end].val==target) {
if (nodeArr[start].index>nodeArr[end].index) {
ret.push_back(nodeArr[end].index);
ret.push_back(nodeArr[start].index);
}elseif(nodeArr[start].index<nodeArr[end].index) {
ret.push_back(nodeArr[start].index);
ret.push_back(nodeArr[end].index);
}
break;
}elseif(nodeArr[start].val+nodeArr[end].val<target){
start++;
}else{
end--;
}
}
return ret;
}
比较笨的算法:
vector<int> twoSum(vector<int> &numbers,int target)
{
vector<int> ret;
for (int i=0; i<=numbers.size()/2; i++) {
for (int j=i+1; j<numbers.size(); j++) {
if (numbers[i]+numbers[j]==target) {
ret.push_back(1);
ret.push_back(2);
return ret;
}
}
}
return ret;
}
该算法复杂度是O(N*N)Two Sum