1 / 5

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

dalmar
Download Presentation

Solution 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 () { 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"; }

More Related