Write a method named kthSmallest
that returns the kth smallest element value in a row/column-sorted 2D square array of integers.
Your method accepts two parameters: a 2D array where each row and each column are arranged in sorted order, and an integer k.
You may assume that the arrays passed as parameters have the same dimensions.
Consider the following matrix:
int[][] matrix = {
{ 1, 2, 5, 14},
{11, 15, 19, 22},
{12, 16, 28, 32},
{20, 22, 29, 35}
};
The matrix is not fully sorted, but notice that each row by itself is sorted, such as row 0, which contains 1, 2, 5, and 14.
Each column is also sorted, such as column 0, which contains 1, 11, 12, and 20.
Given the preceding matrix, the call of kthSmallest(matrix, 8)
would return 16
since that is the array's 8th smallest element.
Assumptions:
You may assume that the array's elements are properly row/column-sorted as described.
You may assume that the matrix is square, meaning that it has the same number of rows and columns, and that each row has the same number of elements.
You may assume that the matrix has at least 1 row and 1 column.
You may assume that the value passed for k is between 1 and the number of elements in the matrix, inclusive.