Search
 
SCRIPT & CODE EXAMPLE
 

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;
    }  
};
Comment

PREVIOUS NEXT
Code Example
Cpp :: c++ CRL multiline string 
Cpp :: run a c++ file in terminal 
Cpp :: variabili in c++ 
Cpp :: fibonacci search algorithm c++ 
Cpp :: private static c++ 
Cpp :: pass address to function c++ 
Cpp :: https://www.google 
Cpp :: 7 9 C:UsersAliyahDocumentsshut up.cpp [Error] expected unqualified-id before string constant 
Cpp :: is plaindrome 
Cpp :: comment savoir si un nombre est premier c++ 
Cpp :: Int main ( ) { int i,n; cinn; i=n; while(i=1) { i=i+5; i=i-6; } } 
Cpp :: how to list directory in c++ 
Cpp :: 1672. Richest Customer Wealth leetcode solution in c++ 
Cpp :: cpp qmenu add custom widget action 
Cpp :: multilevel inheritance in c++ private method 
Cpp :: MPI_File_seek 
Cpp :: what is a string called in c++ 
Cpp :: sum of 2 arrays c++ 
Cpp :: how to calculate the sum of primary diagonal matrix and secondary diagonal matrix using c++ 
Cpp :: how to declare a function in c++ header file 
Cpp :: How to get the last element of an array in C++ using std::array 
Cpp :: how to write hello world c++ 
Cpp :: c++ for 
Cpp :: can derived class access private members 
Cpp :: cout<<"helloworld"<<endl problem 
C :: powershell search files for string 
C :: convert from integer to string vb 
C :: react-textfit 
C :: type change in c 
C :: c format specifiers 
ADD CONTENT
Topic
Content
Source link
Name
4+9 =