public class Solution {
public int KthSmallest(int[,] matrix, int k) {
var row = matrix.GetLength();
var col = matrix.GetLength(); var list = new List<int>(); for (int i = ; i < row; i++)
{
for (int j = ; j < col; j++)
{
list.Add(matrix[i, j]);
}
} list = list.OrderBy(x => x).ToList();
return list[k - ];
}
}
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/#/description
补充一个多次使用二分查找的解决方案:
public class Solution {
public int KthSmallest(int[][] matrix, int k) {
int low = matrix[][];
int high = matrix[matrix.Length - ][matrix[].Length - ];
int count = ;
while (low <= high)
{
int mid = low + (high - low) / ;
count = GetCount(matrix, mid);
if (count < k)
{
low = mid + ;
}
else
{
high = mid - ;
}
}
return low;
} private int GetCount(int[][] matrix, int num)
{
int ans = ;
int i = ;
int j = matrix[].Length - ;
while (i < matrix.Length && j >= )
{
if (matrix[i][j] > num)
{
j--;
}
else
{
ans += j + ;
i++;
}
}
return ans;
}
}