The problem is simple if I sort all the values and pick the fist K values. But it wastes too much time because maybe the smallest K values has been sorted before the whole array is sorted. I think the way to solve this problem is to add a flag in the code, but I can not figure out how to put the flag to judge whether the smallest k values has been sort.
Share
You can use random selection algorithm to solve this problem with O(n) time. In the end, just return sub-array from 0 to k.