1. Two Sum
1. Two Sum
Description:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路
假设这些数排好序了, 那么我们只需要使用双指针即可在O(n)的时间内解决此问题。代码如下:
class Solution {
public:
static bool cmp(const pair<int, int>& a, const pair<int, int>& b) {
return a.first < b.first;
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<pair<int, int> > num;
for(int i=0; i<nums.size(); i++) {
num.push_back(make_pair(nums[i], i));
}
sort(num.begin(), num.end(), cmp);
int i = 0, j = nums.size()-1;
vector<int> res;
while(i < j) {
int a = num[i].first;
int b = num[j].first;
if(a+b > target) j--;
else if(a+b < target) i++;
else {
res.push_back(num[i].second);
res.push_back(num[j].second);
break;
}
}
return res;
}
};