借助map辅助:
class Solution { public: /** * * @param numbers int整型vector * @param target int整型 * @return int整型vector */ vector twoSum(vector &numbers, int target) { // write code here unordered_map m; // 1. 存储下标到map for (int i = 0; i < numbers.size(); ++i) m[numbers[i]] = i + 1; // 2. 再次扫描序列 for (int i = 0; i < numbers.size(); ++i) { if (m.find(target - numbers[i]) != m.end()) { int idx = m[target - numbers[i]]; vector vec = {i + 1, idx}; if (idx > i + 1) return vec; } } } };