标签:
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)暴力
O(n^2) runtime O(1) space
Loop through each element x and find if there is another value that equals to target – x.
(2)hash
O(1) runtime O(n) space
using a hash map that maps a value to its index.
code:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int i, sum; vector<int> results; map<int, int> hmap; for(i=0; i<nums.size(); i++){ if(!hmap.count(nums[i])){ hmap.insert(pair<int, int>(nums[i], i)); } if(hmap.count(target-nums[i])){ int n=hmap[target-nums[i]]; if(n<i){ results.push_back(n+1); results.push_back(i+1);
return results; } } } return results; } };
标签:
原文地址:http://www.cnblogs.com/xuanyuanchen/p/4460783.html