标签:style blog color io os ar strong for sp
题目描述:
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
解题方案:
定义一个结构体,用来存储原数组中的值和位置,然后对原数组按值进行排序,得到新数组。对新数组按首尾向中间遍历。下面是该题的代码:
1 struct number_and_location{ 2 int number; 3 int location; 4 bool operator < (const number_and_location& lhs)const { 5 return number < lhs.number; 6 } 7 }; 8 9 class Solution { 10 public: 11 vector<int> twoSum(vector<int> &numbers, int target) { 12 int len_of_numbers = numbers.size(); 13 vector<int> index_of_result(2, 0); 14 vector<number_and_location> change_of_source; 15 for(int i = 0; i < len_of_numbers; ++i){ 16 change_of_source.push_back((number_and_location){numbers[i],i}); 17 } 18 sort(change_of_source.begin(),change_of_source.end()); 19 int j = len_of_numbers - 1; 20 int i = 0; 21 while ( j != i){ 22 if(change_of_source[i].number + change_of_source[j].number == target){ 23 if(change_of_source[i].location < change_of_source[j].location){ 24 index_of_result[0] = change_of_source[i].location + 1; 25 index_of_result[1] = change_of_source[j].location + 1; 26 }else { 27 index_of_result[0] = change_of_source[j].location + 1; 28 index_of_result[1] = change_of_source[i].location + 1; 29 } 30 break; 31 }else if(change_of_source[i].number + change_of_source[j].number < target){ 32 ++i; 33 }else { 34 --j; 35 } 36 } 37 return index_of_result; 38 } 39 };
标签:style blog color io os ar strong for sp
原文地址:http://www.cnblogs.com/skycore/p/4001103.html