50 likes | 179 Views
Problem: Given an array of positive integers, find a pair of integers in the array that adds up to 10 (or indicate none exist). Your code should be as efficient as possible. Solution 1.
E N D
Problem: Given an array of positive integers, find a pair of integers in the array that adds up to 10 (or indicate none exist). Your code should be as efficient as possible.
Solution 1 for (i=0, i<size, i++){ for (j=0, j<size, j++) { if (a[i]+a[j]==10)cout<< a[i]<<"plus"<< a[j[<<“=10"; else cout << “NO such pair exists” }}
Solution 2 int count = 0;for (i=0, i<size, i++){for (j=0, j<size, j++){ if (i!=j) { if (a[i]+a[j]==10) {cout<< a[i]<<"plus"<< a[j[<<“=10"; count++; } }}}if (count == 0)cout<<"no such pair exists";
Solution 3 Boolean foundPair = false;for (i=0, i<size, i++){ for (j=i+1, j<size, j++) { if (a[i]+a[j]==10) {cout<< a[i]<<"plus"<< a[j[<<“=10"; foundPair = true; break; } }}if (!foundPair)cout<<"no such pair exists";
Solution 4 void main () { constint SIZE = 15; constint SUM = 10; boolfoundPair = false; inta[SIZE]; boolsee[SUM+1] = {false}; for (int i=0; i < SIZE && !foundPair; i++) { if (see[SUM-a[i]]) { cout << a[i] << " " << SUM-a[i] << "Exist in array and add to " << SUM << "\n" ; foundPair= true; } see[a[i]] = true; } if (! foundPair) cout << " Sum not found"; }