题目:
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
我自己写了一个解法:
是设置了一个结构体存储原下标和相应数值,然后设置该结构体类型的容器并对其进行排序后处理。代码如下:
#include#include #include using namespace std; typedef struct m_data { int num; int index; }m_data; bool SortBynum(const m_data &R1,const m_data &R2)//容器的比较函数 { return (R1.num < R2.num);//升序排列 } vector twoSum(vector &numbers, int target) { vector mydata; for (int i = 0; i < numbers.size(); i++)//扫描遍历复制 { m_data temp; temp.num = numbers[i]; temp.index = i; mydata.push_back(temp); } vector result; sort(mydata.begin(),mydata.end(),SortBynum); //按升序排列 for (int i = 0; i < mydata.size(); i++) { cout< mydata[j].index ) { result.push_back(mydata[j].index); result.push_back(mydata[i].index); } else { result.push_back(mydata[i].index + 1); result.push_back(mydata[j].index + 1); } cout< target)//大于时,直接进入下一次的循环,节约时间成本 { break; } } return result; } //测试用 int main() { vector numbers; numbers.push_back(3); numbers.push_back(2); numbers.push_back(4); numbers.push_back(9); twoSum(numbers,7); system("pause"); return 1; }
但是leecode说无法编译sort函数,不知道如何加入#include
代码如下:
#include#include #include #include