本文共 1049 字,大约阅读时间需要 3 分钟。
问题:
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
哈希的思想,将每个数存为数对pair(num, index), 遍历数组的时候 查找target-num是否存在,如果存在取出index.
class Solution {public: vector twoSum(vector &numbers, int target) { mapmy_map; vector m_result; for(int i= 0; i<=numbers.size();i++) { if(my_map.count((target-numbers[i])) == 1) { m_result.push_back(my_map[target-numbers[i]]+1); m_result.push_back(i+1); break; } else { my_map[numbers[i]] = i; } } return m_result; }};
转载地址:http://rztsi.baihongyu.com/