MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / kthSmallest

Method kthSmallest

KthSmallestElementInASortedMatrix.java:2–26  ·  view source on GitHub ↗
(int[][] matrix, int k)

Source from the content-addressed store, hash-verified

1class Solution {
2 public int kthSmallest(int[][] matrix, int k) {
3 if(matrix==null) return 0;
4 int r=matrix.length;
5 int c=matrix[0].length;
6 int startVal=matrix[0][0],endVal=matrix[r-1][c-1],midVal;
7 while(startVal<=endVal)
8 {
9 midVal=(endVal+startVal)/2;
10 int ans=0;
11 for(int i=0;i<r;i++)
12 {
13 int l=0,h=c-1;
14 while(l<=h)
15 {
16 int m=l+(h-l)/2;
17 if(matrix[i][m]<=midVal) l=m+1;
18 else h=m-1;
19 }
20 ans+=l;
21 }
22 if(ans<k) startVal=midVal+1;
23 else endVal=midVal-1;
24 }
25 return startVal;
26 }
27}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected