[Leetcode]Two Sum
2013-10-17 10:16 qingmarch 阅读(353) 评论(0) 收藏 举报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
思路:使用一个struct保留排序前的下标号,然后设置两个下标index1,index2依次从前往后,从后往前
1 class Solution { 2 public: 3 struct node{ 4 int val; 5 int index; 6 }; 7 bool compare(const node& a, const node& b){ 8 return a.val < b.val; 9 } 10 vector<int> twoSum(vector<int> &numbers, int target) { 11 vector<int> result; 12 int index1 = 0; 13 int index2 = 0; 14 vector<node> resu_node; 15 node temp; 16 for(int i = 0;i < numbers.size();i++) 17 { 18 temp.index = i + 1; 19 temp.val = numbers[i]; 20 resu_node.push_back(temp); 21 } 22 23 sort(resu_node.begin(),resu_node.end(),compare); 24 25 for(int i = 0,j = resu_node.size() - 1; i < j;) 26 { 27 if(resu_node[i].val + resu_node[j].val == target){ 28 index1 = resu_node[i].index; 29 index2 = resu_node[j].index; 30 result.push_back(index1); 31 result.push_back(index2); 32 break; 33 }else if(resu_node[i].val + resu_node[j].val > target){ 34 j--; 35 }else{ 36 i++; 37 } 38 } 39 40 41 42 return result; 43 } 44 };
浙公网安备 33010602011771号