題目:
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這個頭文件,於是在網上查了下有沒有其他解法,找到一個利用map實現的方法,覺得很棒,原文地址:http://blog.csdn.net/pickless/article/details/8995612,代碼很短小精悍,也節省了一部分時間復雜度,非常喜歡,記錄下來:
代碼如下:
#include#include #include #include