題目
這個問題的最基本形式是這樣:給你一個數組和一個整數target,可以保證數組中存在兩個數的和爲target,請你返回這兩個數的索引。
比如輸入nums = [3,1,3,6],target = 6,算法應該返回數組[0,2],因爲 3 + 3 = 6。
這個問題如何解決呢?首先最簡單粗暴的辦法當然是窮舉了,這個解法非常直接,時間複雜度 O(N^2),空間複雜度 O(1)。
更好一點的解法,可以通過一個哈希表減少時間複雜度。
這樣,由於哈希表的查詢時間爲 O(1),算法的時間複雜度降低到 O(N),但是需要 O(N) 的空間複雜度來存儲哈希表。不過綜合來看,是要比暴力解法高效的。
代碼
實現代碼如下:
#include <iostream>
#include <map>
using namespace std;
// 簡單的暴力搜索
bool two_sum(int* array, int len, int target, int* i, int* j) {
for (int x = 0; x < len; x++)
for (int y = x + 1; y < len; y++)
if (array[x] + array[y] == target) {
*i = x;
*j = y;
return true;
}
return false;
}
// hashMap
bool hash_TwoSum(int* array, int len, int target, int* i, int* j) {
map<int, int>index;
map<int, int>::iterator it;
for (int x = 0; x < len; x++)
index[array[x]] = x;
for (int x = 0; x < len; x++) {
int other = target - array[x];
it = index.find(other);
if (it!= index.end() && it!= index.find(array[x])) {
*i = x;
*j = it->second;
return true;
}
}
return false;
}
int main() {
int nums[] = { 3,1,3,6 }, target = 7;
int i, j,len=end(nums)-begin(nums);
if (two_sum(nums, len, target, &i, &j))
cout << i << " " << j << endl;
if (hash_TwoSum(nums, len, target, &i, &j))
cout << i << " " << j << endl;
else cout << "Not exist!";
system("pause");
return 0;
}