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
题目意思是:给定一个数组,给一个数target,在数组找到两个数的和为target,找出这个两个数的位置,其下标索引从1开始算起。
思路:
方法一:暴利求,两个for循环遍历,找到退出,复杂度O(n2)
方法二::hash 用一个哈希表,存储每个数对应的下标,复杂度 O(n).
方法二解答:
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { unordered_map<int, int> mapping; vector<int> result; for (int i = 0; i < numbers.size(); ++i) { mapping[numbers[i]] = i; } for (int i = 0; i < numbers.size(); ++i) { const int tmp = target - numbers[i]; if (mapping.find(tmp) != mapping.end() && mapping[tmp]>i) { result.push_back(i+1); result.push_back(mapping[tmp] + 1); break; } } return result; } };在线推送结果为:
Question:
Similar to Question [1. Two Sum], except that the input array is already sorted in
ascending order.
问题:假如数组是有序的话我们就可以同时从头尾开始向中遍历。
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; int i = 0; int j = numbers.size() - 1; while (i < j) { int sum = numbers[i] + numbers[j]; if (sum < target) ++i; else if (sum>target) --j; else { result.push_back(i + 1); result.push_back(j + 1); break; } } return result; } };
leetcode---------------Two Sum
原文地址:http://blog.csdn.net/chenxun_2010/article/details/42499199