You have a list of n integers and you want the x smallest. For example,
x_smallest([1, 2, 5, 4, 3], 3)
should return [1, 2, 3]
.
I'll vote up unique runtimes within reason and will give the green check to the best runtime.
I'll start with O(n * x)
: Create an array of length x. Iterate through the list x times, each time pulling out the next smallest integer.
Edits
- You have no idea how big or small these numbers are ahead of time.
- You don't care about the final order, you just want the x smallest.
- This is already being handled in some solutions, but let's say that while you aren't guaranteed a unique list, you aren't going to get a degenerate list either such as
[1, 1, 1, 1, 1]
either.