LeetCode#1.Two Sum
题目
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.
思路
第一个想法是找出在给出的数中两两组合,若和为目标则存入结果。但这样复杂度为O(n2),显然需要改进。
改进的思路:使用哈希函数的思想。用map存储对,扫描数组,对于当前的数算出另一个数,如果map中有这个记录,则返回结果。否则把当前的数存入map,置其值为序号。
代码
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { if (nums.size() == 0) return *new vector<int>(0, 0); map<int, size_t> hash; for (int i = 0; i < nums.size(); ++i) { int other = target - nums[i]; if (hash[other] != 0) { vector<int> result; result.push_back(hash[target - nums[i]]-1); result.push_back(i); return result; } else hash[nums[i]] = i+1; } vector<int> tmp; return tmp; }