两数之和 hash
作者:
Gtea
,
2022-01-21 21:48:24
,
所有人可见
,
阅读 162
哈希表 ---时间复杂度O(n)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
using namespace std;
unordered_map<int ,int > has;
const int N = 1001001;
int res[N] , n , tag ,temp;
int main()
{
cin >> n >> tag;
for(int i = 0; i <= n - 1 ; i ++)
{
cin >> res[i];
int t = tag - res[i];
if(has.count(res[i])) //count是找键的
{
cout << has[res[i]] << " " << i;
break;
}
has[t] = i;
}
}
二分优化 ---时间复杂度O(nlogn)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
using namespace std;
unordered_map<int ,int > has;
const int N = 1001001;
int res[N] , n , tag ,temp;
int main()
{
cin >> n;
for(int i = 0; i <= n - 1 ; i ++) cin >> res[i];
sort(res, res + n);
cin >> tag;
for(int i = 0; i < n ; i ++)
{
int t = tag - res[i];
int l = 0 , r = n - 1;
while(l < r)
{
int mid = l + r >> 1;
if(res[mid] >= t) r = mid;
else l = mid + 1;
}
if(res[r] == t){cout << i << " " << r; break;}
}
}