[LeetCode-1] Two Sum
Two Sum
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, 2, 4, 4, 5] 8)的坑=。=没考虑这个导致输出的结果是[3, 3]而不是[3, 4]……要注意这些烦人的badcase呀……
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int> &numbers, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 unordered_map<int, int> num_map; 7 vector<int> result; 8 int index; 9 num_map.clear(); 10 for (int i = 0; i < numbers.size(); ++i) { 11 num_map.insert(pair<int, int>(numbers.at(i), i)); 12 if (target / 2 == numbers.at(i) && target % 2 == 0) { 13 result.push_back(i + 1); 14 if (2 == result.size()) { 15 return result; // fucking badcase 16 } 17 } 18 } 19 result.clear(); 20 unordered_map<int, int>::iterator iter; 21 for (int i = 0; i < numbers.size(); ++i) { 22 if (num_map.end() != (iter = num_map.find(target - numbers.at(i)))) { 23 result.push_back(i + 1); 24 result.push_back(iter->second + 1); 25 } 26 } 27 return result; 28 } 29 };
浙公网安备 33010602011771号