Given a list of sequence number in an array, starting from 1 - N, find the missing number.
Solution#1:
If array is sorted, O(log(n)) will be the best approach. Divide the number to half, compare the value of middle element with the index+1. If the same, missing number is located in left, else it is located in right. Then divide the half to another half and proceed with same approach as above.
Solution#2:
If array is unsorted, N = length of array+1, sum = N*(N+1)/2. Then loop through the array and minus the value of array with sum. At the end of loop, the remaining value in sum is the missing number. O(N) approach.
Friday, December 12, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment