题目:
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.
从给定的一个整数数组中找出两个数,使得它们的和为target,并返回两个数在原数组中的下标
思路:
1. 对数组进行排序,为了方便获取排序后的原下标,采用multimap(map不允许重复的keys值)
multimap不能用 [key] = value的方式来行赋值,但是map可以
2. 用两个游标(i = 0, j = size - 1)分别从数组的两头开始,如果
1) nums[i] + nums[j] > target 大于目标值,则将j往前移一位
2) nums[i] + nums[j] < target 小于目标值,则将i往后移一位
3) nums[i] + nums[j] = target 完成~
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int nsize = nums.size();
multimap<int, int> _n_i;
for(int i = ; i < nsize; i++)
_n_i.insert(pair<int,int>(nums[i], i)); vector<int> result;
multimap<int, int>::iterator _it_begin = _n_i.begin();
multimap<int, int>::iterator _it_end = _n_i.end();
--_it_end;
while(true){
int tmp = _it_begin->first + _it_end->first;
if(tmp < target)
++_it_begin;
else if(tmp > target)
--_it_end;
else{
int i = _it_begin->second;
int j = _it_end->second;
if(i > j){
int _tmp = i;
i = j;
j = _tmp;
}
result.push_back(i);
result.push_back(j);
return result;
}
}
}
};