+ 5
How do you find the missing number in a given integer array of 1 to 100 in c?
9 Respostas
+ 12
There's a really cool algortihm for that. It's so simple that you wonder how you didn't think of it, but you'd just never think of it on your own.
First, take the sum of all numbers from 1 to 100, I think that's 5050.
Then you run through the array and keep subtracting. Whatever is leftover is your missing number :)
+ 6
Maneren That only works if the array is sorted though đ
+ 5
I'd probably make an array of 100 bools (or ints in C) and set them all to false/0 by default. Then iterate over the integer array once and for every number in the array set the according element in the bool array to true/1. Then iterate over the bool array and check which value is false/0. Might not be the most efficient solution, but it's probably still better than anything that needs 100*100 = 10,000 iterations...
+ 4
If the difference between two consecutive array elements is greater than 1 then that element is missing. You can loop through the array elements and brake your loop when the difference is greater than 1đ
+ 3
Or, iterate through and check if greater neighbor number is +1. If +2 there is missing one.
The code for this:
https://code.sololearn.com/cyrc24RUSqFm/?ref=app
+ 2
Schindlabua That's probably unbeatable đđ
+ 1
Anna Yeah, kinda missed this fact.
+ 1
You can compare a value of an array and its index plus some offset of the start sequence. For example:
https://code.sololearn.com/cwcNIwGpFf3u/?ref=app
This works only for sorted arrays. So if one is not sorted sort it.
0
There's another solution by using arithmetic progression property such
@Schindlabua suggested.
https://code.sololearn.com/cwfwfu58Fds8/?ref=app