Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

378. Kth Smallest Element in a Sorted Matrix using binary search

class Solution {
public:
    //from left-bottom or right-top, count how many numbers are less equal than mid
    int solve(vector<vector<int>>& matrix, int mid){
        int count = 0, n = matrix.size(), i = n-1, j = 0;
        while(i >= 0 && j < n){
            if(matrix[i][j] > mid) i--;
            else{
                count += (i+1);
                j++;
            }
        }
        return count;
    }
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        int n = matrix.size(), i = matrix[0][0], j = matrix[n-1][n-1];
        while(i < j){
            int mid = i + (j-i)/2;
            int posi = solve(matrix, mid);
            if(posi < k) i = mid+1;
            else j = mid;
        }
        return i;
    }  
};
 
PREVIOUS NEXT
Tagged: #Kth #Smallest #Element #Sorted #Matrix #binary #search
ADD COMMENT
Topic
Name
4+7 =