標籤:
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
給一個vector,一個value,要求求出vector之內的兩數相加之和等於value的兩個index。
這裡的基本思想是用一個map先來儲存vector元素的值與他們對應的index,然後迴圈vector,用value減去每個數之後,把差值直接放到map裡面去尋找
看能不能找到對應的index,大體上就是這個思想,下面詳見代碼:
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 map<int, int> index; 5 vector<int> result; 6 int sz = nums.size(); 7 for (int i = 0; i < sz; ++i){ 8 index[nums[i]] = i; 9 }10 map<int, int>::iterator it;11 for (int i = 0; i < sz; ++i){12 if ((it = index.find(target - nums[i])) != index.end()){13 if (it->second == i) continue;//這一步要注意,防止找到的index與當前的i是相等的14 result.push_back(i + 1);15 result.push_back(it->second + 1);16 break;17 }18 }19 return result;20 }21 };
LeetCode OJ:Two Sum(兩數之和)