The seemingly clever answer of keeping the counts doesn't hold when you are given the array.
Counting is O(n)
, and so is linear search. Thus, counting is not optimal!
Binary search is your friend, and can get things done in O(lg n)
time, which as you may know is way better.
Of course, if you have to process the array anyways (reading from a file, user input etc.), make use of that time to just count the number of 1s
and 0s
and be done with it (you don't even have to store any of it, just keep the counts).
To drive the point home, if you are writing a library, which has a function called getFirstOneIndex(sortZeroesOnesArr: Array[Integer]): Integer
that takes a sorted array of ones and zeroes and returns the position of the first 1
, do not count, binary search.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…