-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution378.cs
55 lines (48 loc) · 1.16 KB
/
Solution378.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
namespace LeetCode.Solutions;
public class Solution378
{
/// <summary>
/// 378. Kth Smallest Element in a Sorted Matrix - Medium
/// <a href="https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix">See the problem</a>
/// </summary>
public int KthSmallest(int[][] matrix, int k)
{
var n = matrix.Length;
var left = matrix[0][0];
var right = matrix[n - 1][n - 1];
while (left < right)
{
var mid = left + (right - left) / 2;
var count = Count(matrix, mid);
if (count < k)
{
left = mid + 1;
}
else
{
right = mid;
}
}
return left;
}
private int Count(int[][] matrix, int target)
{
var n = matrix.Length;
var count = 0;
var i = n - 1;
var j = 0;
while (i >= 0 && j < n)
{
if (matrix[i][j] <= target)
{
count += i + 1;
j++;
}
else
{
i--;
}
}
return count;
}
}