两数之和
Posted zhou753099943
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两数之和相关的知识,希望对你有一定的参考价值。
/*
* 两数之和
给定一个整数数组nums和一个整数目标值target,
请你在该数组中找出和目标值target相等的两个整数,并返回它们的下标
*/
struct NodeIndex
{
NodeIndex(){}
NodeIndex(int i, int v): index(i), value(v){}
int index = 0;
int value = 0;
};
void getSumTarget()
{
std::vector<int> nums;
nums.push_back(1);
nums.push_back(4);
nums.push_back(6);
nums.push_back(100);
nums.push_back(5);
nums.push_back(5);
nums.push_back(2);
nums.push_back(8);
nums.push_back(9);
std::vector<NodeIndex> postion;
for (size_t i = 0; i < nums.size();++i)
{
postion.push_back(NodeIndex(i, nums[i]));
std::cout<<"("<<i<<","<<nums[i]<<"),";
}
std::cout<<std::endl;
int target = 10;
std::sort(postion.begin(), postion.end(), [](NodeIndex a, NodeIndex b){
return a.value < b.value;
});
for (const NodeIndex& it : postion)
{
std::cout<<it.value<<",";
}
std::cout<<std::endl;
int min = nums.at(0);
if(target < min)
return;
std::vector<std::pair<int, int>> target_nums;
int left_index = 0;
int right_index = nums.size() - 1;
while (left_index < right_index)
{
NodeIndex node1 = postion[left_index];
NodeIndex node2 = postion[right_index];
int sum = node1.value + node2.value;
if (sum == target)
{
target_nums.push_back(std::make_pair(node1.index,node2.index));
left_index++;
right_index--;
}
else if (sum > target)
right_index--;
else
left_index++;
}
for(auto it : target_nums)
{
std::cout<<"["<<it.first<<","<<it.second<<"]|";
}
std::cout<<std::endl;
}
以上是关于两数之和的主要内容,如果未能解决你的问题,请参考以下文章