标签:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Tags: Array Hash Table
Similar Problems: (M) 3Sum (M) 4Sum (M) Two Sum II - Input array is sorted (E) Two Sum III - Data structure design
1 #include <vector> 2 #include <map> 3 using namespace std; 4 class Solution { 5 public: 6 vector<int> twoSum(vector<int>& nums, int target) { 7 std::multimap<int, int> idx2Num; 8 std::vector<int>::iterator itVec = nums.begin(); 9 int idx = 0; 10 while (itVec != nums.end()) 11 { 12 idx2Num.insert(std::make_pair(*itVec, idx)); 13 idx++; 14 itVec++; 15 } 16 std::vector<int> numsSorted; 17 std::multimap<int, int>::iterator itMap_Fir = idx2Num.begin(); 18 std::multimap<int, int>::iterator itMap_Sec = idx2Num.end(); 19 itMap_Sec--; 20 21 int sum = itMap_Fir->first + itMap_Sec->first; 22 while (sum != target) 23 { 24 if (sum > target) 25 { 26 itMap_Sec--; 27 } 28 else 29 { 30 itMap_Fir++; 31 } 32 sum = itMap_Fir->first + itMap_Sec->first; 33 } 34 numsSorted.push_back(itMap_Fir->second); 35 numsSorted.push_back(itMap_Sec->second); 36 return numsSorted; 37 38 } 39 };
本算法对数组进行排序采用了取巧的方法,即使用多重map。
若不用map,对Vector进行排序可采用:
标签:
原文地址:http://www.cnblogs.com/whl2012/p/5575083.html