leetcode378

public class Solution {
    public int KthSmallest(int[,] matrix, int k) {
        var row = matrix.GetLength(0);
            var col = matrix.GetLength(1);

            var list = new List<int>();

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    list.Add(matrix[i, j]);
                }
            }

            list = list.OrderBy(x => x).ToList();
            return list[k - 1];
    }
}

https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/#/description

补充一个多次使用二分查找的解决方案:

 1 public class Solution {
 2     public int KthSmallest(int[][] matrix, int k) {
 3         int low = matrix[0][0];
 4         int high = matrix[matrix.Length - 1][matrix[0].Length - 1];
 5         int count = 0;
 6         while (low <= high)
 7         {
 8             int mid = low + (high - low) / 2;
 9             count = GetCount(matrix, mid);
10             if (count < k)
11             {
12                 low = mid + 1;
13             }
14             else
15             {
16                 high = mid - 1;
17             }
18         }
19         return low;
20     }
21     
22     
23     private int GetCount(int[][] matrix, int num)
24     {
25         int ans = 0;
26         int i = 0;
27         int j = matrix[0].Length - 1;
28         while (i < matrix.Length && j >= 0)
29         {
30             if (matrix[i][j] > num)
31             {
32                 j--;
33             }
34             else
35             {
36                 ans += j + 1;
37                 i++;
38             }
39         }
40         return ans;
41     }
42 }
原文地址:https://www.cnblogs.com/asenyang/p/6848512.html