Last active
December 17, 2015 19:09
-
-
Save quangnguyenbh/5658010 to your computer and use it in GitHub Desktop.
Q. Write a O(N^2) function that takes as input an array of N integers, return a bool to indicate whether there are three integers in the array such that the sum of the three is zero.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 1. Sort the array A[1..n] incrementally. | |
| 2. | |
| process ( A[1..n]) | |
| begin | |
| if(n < 3) | |
| return false | |
| else if (A[1] > 0 or A[n] < 0 ) | |
| return false | |
| else if (A[1] + 2A[n] < 0) | |
| return process(A[2..n]) | |
| else if ( 2A[1] + A[n] > 0) | |
| return process(A[1..n-1]) | |
| else | |
| loop from i = n to 3 | |
| begin | |
| if( A[1] + 2A[i] >= 0) | |
| loop from k = 2 to i-1 | |
| begin | |
| if( A[1] + A[k] + A[i] > 0) | |
| break | |
| else if(A[1] + A[k] + A[i] == 0) | |
| return true | |
| else continue | |
| end | |
| else | |
| process( A[2..n] ) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment