经典指数          
原因
3132
浏览数
0
收藏数
 

请设计一个高效算法,找出数组中两数之和为指定值的所有整数对。 给定一个int数组A和数组大小n以及需查找的和sum,请返回和为sum的整数对的个数。保证数组大小小于等于3000。 测试样例: [1,2,3,4,5],5,6 返回:2

     举报   纠错  
 
切换
1 个答案

搞清楚配对的意义即可 例如 1,1,1  和 为2 那么 有3种配法 第一个1与后两个1配,第2个与第3个陪。而对于 1,2,2

陪 3 可以是 (1,2),( 1,2) 知道这点就行了。

下面的代码map计数,遍历map并查找sum - it->first       如果是一个数,则为等差数列求和

为配对个数,

如果是两个不同的数, 其数量和为配对个数

class FindPair {

public:

int countPairs(vector A, int n, int sum) {

map st;

int cnt = 0;

for(int i = 0; i < A.size(); i++) st[A[i]]++;

for(map::iterator it = st.begin(); it != st.end(); it++){

map::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;

}

};

 
切换
撰写答案