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在線推送結果為:twoSum(vector &numbers, int target) { unordered_map mapping; vector 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: vectortwoSum(vector &numbers, int target) { vector 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; } };