Horje
378. Kth Smallest Element in a Sorted Matrix using binary search Code Example
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;
    }  
};




Cpp

Related
get player pawn Code Example get player pawn Code Example
sfml hide message Code Example sfml hide message Code Example
convert c code to java online free Code Example convert c code to java online free Code Example
unknown amount of threads cpp Code Example unknown amount of threads cpp Code Example
c++ correct upto 3 decimal places Code Example c++ correct upto 3 decimal places Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
7