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
代码如下:
online judge的时间为