c++ - Algorithm to count the number of pairs whose sum exists in the array -
given array of n integers. how can count number of pairs sum exists in array?
e.g. int a[] = {1, 3, 4, 6, 7}
. here there 3 such pairs: (1 + 3) = 4, (3 + 4) = 7, (1+6) = 7.
there no duplicate numbers in given array , array not sorted.also array can changed,its not necessary maintain array.
i have tried following 2 codes want reduce complexity of code less o(n^2).
try 1:(complexity o(n^3))
#include<iostream> #include<vector> #include<algorithm> using namespace std; main(){ int i,input,j,n,ans=0,sum; cin>>n; vector<int> vec; for(i=0;i<n;i++){ cin>>input; vec.push_back(input); } for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ sum=vec[i]+vec[j]; if(find(vec.begin(),vec.end(),sum)!= vec.end()){ ans++; } } } cout<<ans; }
i'm not sure if reduce complexity, think it's simpler way since don't declare variables in function you're using, saving memory , time:
#include<iostream> #include<vector> #include<algorithm> using namespace std; bool checkforeveryelement(vector<int> vec,int sum) { for( int i=0; i<vec.size(); i++) { for(int j=i+1; j<vec.size(); j++) if(vec[i] + vec[j] == sum) return 1; } return 0; } void main(){ int i,input,j,n,ans=0,sum; cin>>n; vector<int> vec; for(i=0;i<n;i++){ cin>>input; vec.push_back(input); } sort(vec.begin(),vec.end()); for(i=0;i<n;i++) if(checkforeveryelement(vec,vec[i])){ ans++; } cout<<ans; }
Comments
Post a Comment