Re: Algorithm to find break in contiguity
- From: gw7rib@xxxxxxx
- Date: 26 Jan 2007 12:29:54 -0800
On 25 Jan, 17:37, use...@xxxxxxxxxxxxxxx wrote:
I need an efficient algorithm for the following problem:
If you have unique N-1 numbers in the range 1 to N, find the missing
number.
Of course if you could generalize that to finding missing k numbers
from a sample of N-k unique numbers that are in the range 1 to N that
would be better.
Thanks,
Bhta
Obviously, one way to solve this is to have an array and simply note
each number as you read it. Another is to look through the list to see
if there is a 1, then look through again to see if there is a 2, etc.
So, to make this a challenge, I'll assume that you are only allowed to
store a constant amount of information, and that the time you spend
must be limited to some number times N. The technical term for this is
O(N) in time and O(1) in space.
Finding one missing number is easy - just add up the numbers you have
and subtract from what you would have if they were all there.
Two missing numbers can be done too - I think I got this solution from
this very newsgroup a bit ago. Add up all the numbers you have, and
subtract from the total to get a number (call it m) which is the sum of
the two missing numbers. So one missing number is more than m/2 and one
is less than m/2.
Now add up all the numbers in the list that are smaller than m/2,
subtract from what the total would be, and bingo! You have the smaller
missing number. And as you know what the two missing numbers add up to,
you can calculate the larger as well.
I'll leave you to think about whether this can be extended to three
numbers, or indeed generalised further. I don't think you can do in
still in O(N) time, but I may be wrong...
Hope this helps.
Paul.
.
- Prev by Date: Re: C++ value from union structure using generic class
- Next by Date: Re: what type of sort is this?
- Previous by thread: Re: Algorithm to find break in contiguity
- Next by thread: Re: Algorithm to find break in contiguity
- Index(es):
Relevant Pages
|