题目描述:
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
代码如下:
C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//不能排序
//存在乱序;
int i = 0;
vector<int> res;
multimap<int, size_t> find_location;
multiset<int> item(nums.cbegin(), nums.cend());
for (auto &r : nums) {
find_location.insert(make_pair(r, i));
i++;
}
auto k = 0;
auto map_it = find_location.cbegin();
while (map_it != find_location.end()) {//遍历map中的所有成员;
k = target - map_it->first;//目标值与成员值相减;
// cout<<"map_it->first:"<<map_it->first<<endl;
if(k!= map_it->first){//当时两个不同的元素相加得到目标数时:
cout<<"2"<<endl;
if (item.find(k) != item.end()) {//相减的结果是否存在于上述数组中
auto y = find_location.find(map_it->first)->second;
auto x = find_location.find(k)->second;
res.push_back(y);
res.push_back(x);
return res;
}
}
else{//当两个相同元素相加得到目标数时:
cout<<"1"<<endl;
auto y = find_location.find(map_it->first)->second;
multimap<int,size_t>::iterator end;
end = find_location.upper_bound(k);
--end;
auto x=(end)->second;
res.push_back(y);
res.push_back(x);
return res;
}
++map_it;
}
}
};
//几个cout语句是用作调试的;
//主要方法是采用了C++的STL库中的multimap和multiset函数,因为之前没怎么用过,查阅了半天的资料才弄出来。。目前没想到别的方法。。
//还有就是在使用迭代器的时候忘了++,要记住。
//结果截图: