Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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.

2 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” } }

3 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";

4 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";

5 Solution 4 void main () { const int SIZE = 15; const int SUM = 10; bool foundPair = false; int a[SIZE]; bool see[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"; }


Download ppt "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."

Similar presentations


Ads by Google