2Sum Problem

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:简单粗暴的方法是对数组进行排序,之后对数组的每一个元素x,求出target-x的差,在它之后的元素中搜索是否有此差值,找到了就返回这两个index。算法的复杂度包括排序的复杂度和搜索的复杂度,是O(N^2)的。

解法2:对数组进行排序,注意保存原下标。然后用两个指针i,j分别指在已排序的数组的头尾,v[i]+v[j]=target则返回对应的index,注意要比较两个index的大小; <target则i++,继续比较;>target则j--继续比较;直至j<=i。
这样算法的负责读包括排序的复杂度和比较的复杂度,为O(N*logN+N)=O(N*logN)的。
代码如下:
class Node{
public:
int val;
int index;
Node(){}
Node(int a,int b):val(a),index(b){}
};
bool compare(const Node& a,const Node& b){
return a.val<b.val;
};
class Solution {
public:
vector<int> twoSum(vector<int> &numbers,int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//sort the array
vector<Node> v;
for(int k=0;k<numbers.size();k++){
v.push_back(Node(numbers[k],k+1));
}
sort(v.begin(),v.end(),compare);
//match
int i = 0;
int j = numbers.size()-1;
vector<int> ret;
while(i<j){
if(v[i].val+v[j].val==target){
ret.push_back(min(v[i].index,v[j].index));
ret.push_back(max(v[i].index,v[j].index));
break;
}else if(v[i].val+v[j].val>target){
j--;
}else{
i++;
}
}
return ret;
}
}; 

online judge的时间为 12 milli secs


解法3:用vector初始化hash_map,key为index+1,value为值,然后对数组中的每一个数,求出target-x的差值,在hash_map中找到这个value,并返回对应的key。
代码如下:
online judge的时间为
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值