28ms Binary Search in C


  • 0
    I
    int kthSmallest(int** matrix, int matrixRowSize, int matrixColSize, int k) {
        int minVal = matrix[0][0];
        int maxVal = matrix[matrixRowSize-1][matrixColSize-1];
        int midVal = 0;
        int count = 0;
        while (minVal < maxVal) {
            midVal = (minVal + maxVal) / 2;
            for (int i  = 0; i < matrixRowSize && matrix[i][0] <= midVal; i++) {
                for (int j = 0; j < matrixColSize; j++) {
                    if (matrix[i][j] <= midVal) {
                        count++;   
                    }
                }
            }
            if (k <= count) {
                maxVal = midVal;
            } else {
                minVal = midVal + 1;
            }
            count = 0;
        }
        return minVal;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.