Đề bài
Return the k-th smallest value of the list (k counts from 1). Quickselect finds it in average O(n) time without sorting everything.
Implement kth_smallest(numbers, k).
Input
numbers: The list of integers. k: Which smallest value to return, starting at 1.
Output
Return the k-th smallest value.
Ràng buộc
1 ≤ k ≤ length ≤ 200,000
Ví dụ
Đầu vào:
numbers = [7, 10, 4, 3, 20, 15]
k = 3
Kết quả mong đợi:
expected = 7
Đầu vào:
std::vector<long long> numbers = {7, 10, 4, 3, 20, 15};
long long k = 3;
Kết quả mong đợi:
long long expected = 7;
Đầu vào:
long[] numbers = new long[] {7, 10, 4, 3, 20, 15};
long k = 3;
Kết quả mong đợi:
long expected = 7;
Giải thích
Sorted: 3, 4, 7, 10, 15, 20; the 3rd smallest is 7.
Đầu vào:
numbers = [5, 5, 1]
k = 2
Kết quả mong đợi:
expected = 5
Đầu vào:
std::vector<long long> numbers = {5, 5, 1};
long long k = 2;
Kết quả mong đợi:
long long expected = 5;
Đầu vào:
long[] numbers = new long[] {5, 5, 1};
long k = 2;
Kết quả mong đợi:
long expected = 5;
Giải thích
Sorted: 1, 5, 5; the 2nd smallest is 5 (duplicates count).
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
You only need the element that would sit in position k after sorting, not the fully sorted list.
Gợi ý 2
Partition around a pivot and recurse or iterate only into the side that can still contain the target rank.
Gợi ý 3
Remember that k is one-based, and duplicates must still count as separate positions.
Độ phức tạp mong đợi
O(n) average time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.