#BS0000186. Phần tử nhỏ thứ K trong ma trận đã sắp xếp (Kth Smallest Element in a Sorted Matrix)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Phần tử nhỏ thứ K trong ma trận đã sắp xếp (Kth Smallest Element in a Sorted Matrix)
Kth Smallest Element in a Sorted Matrix
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
You are given an integer matrix , with rows and columns numbered from to . Every row is sorted in non-decreasing order from left to right, and every column is sorted in non-decreasing order from top to bottom. Values may repeat and may be negative.
Take all entries and sort them in non-decreasing order, counting equal entries from different cells separately. Return the value at the -th position, numbered from .
Input
- The first line contains integers and , the matrix size and the required position.
- Each of the next lines contains exactly integers , in left-to-right order for row .
Output
- Print one integer: the -th smallest matrix entry when repetitions are counted.
Subtasks
- Subtask 1 (20 points): ; ; for all ; all rows and columns are non-decreasing.
- Subtask 2 (30 points): ; ; for all ; all rows and columns are non-decreasing.
- Subtask 3 (50 points): ; ; for all ; all rows and columns are non-decreasing.
Examples
Example 1
Input
3 8
1 5 9
10 11 13
12 13 15
Output
13
Explanation
Here and . Sorting the nine entries gives . Both occurrences of must be counted; they occupy positions and . The eighth entry is therefore 13.
Example 2
Input
1 1
-5
Output
-5
Explanation
There is only one matrix entry, , which is the first and only element of the sorted sequence. Hence the answer is -5.