《Cracking the Coding Interview程式設計師面試金典》----整數對查詢

塵封的記憶0發表於2017-05-03
時間限制:3秒 空間限制:32768K 熱度指數:804
本題知識點: 程式設計基礎
 演算法知識視訊講解

題目描述

請設計一個高效演算法,找出陣列中兩數之和為指定值的所有整數對。

給定一個int陣列A和陣列大小n以及需查詢的和sum,請返回和為sum的整數對的個數。保證陣列大小小於等於3000。

測試樣例:
[1,2,3,4,5],5,6

返回:2

思路:map計數,遍歷map並查詢sum - it->first       如果是一個數,則為等差數列求和 為配對個數,

如果是兩個不同的數, 其數量和為配對個數
程式碼如下:
#include<iostream>
#include<vector>
#include<map>
#include<queue>
#include<algorithm>
#include<set>
using namespace std;
int countPairs(vector<int> A, int n, int sum) {
	map<int, int> st;
	int cnt = 0;
	for (int i = 0; i < A.size(); i++) st[A[i]]++;
	for (map<int, int>::iterator it = st.begin(); it != st.end(); it++){
		map<int, int>::iterator ifind = st.find(sum - (it->first));
		if (ifind != st.end() && ifind != it){
			cnt += (it->second * ifind->second);
			it->second = ifind->second = 0;
		}
		else if (ifind != st.end()){
			cnt += ifind->second*(ifind->second - 1) / 2;
			ifind->second = 0;
		}
	}
	return cnt;
}


int main()
{
	vector<int> v;
	int m;
	int temp;
	int sum;
	while (cin >> m >> sum)
	{
		v.clear();
		for (int j = 0; j < m; j++)
		{
			cin >> temp;
			v.push_back(temp);
		}
		cout<<countPairs(v, m, sum)<<endl;
	}
	return 0;
}

不懂的可以加我的QQ群:261035036(IT程式設計師面試寶典

群) 歡迎你到來哦,看了博文給點腳印唄,謝謝啦~~



相關文章