378. Find the kth smallest number in at row and column sorted matrix

/*
 *  378. Find the kth smallest number in at row and column sorted matrix.
 */
public class KthSmallest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[][] matrix = {
                          {1 ,5 ,7},
                          {3 ,7 ,8},
                          {4 ,8 ,9},
                    };
        KthSmallest ks = new KthSmallest();
        
        int k = 4;
        int res = ks.kthSmallest(matrix, k);
        System.out.println("res: " + res);
    }
    
    /*
     *  解題報(bào)告:
             Java 1ms nlog(max -min) solution
        Main loop is binary search of max - min.
        Swap from left-bottom to right-top can get count <= mid in O(n) time instead of O(nlogn), 

        total complexity will be O(nlogm) while m = max - min.
        ref: https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/#/solutions
     */
    public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
        int lo = matrix[0][0], hi = matrix[n-1][n-1];
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            int cout = getLessEqual(matrix, mid);
            
            if (cout < k) lo = mid + 1;
            else 
                hi = mid - 1;
        }
        return lo;
            
    }
    
    public int getLessEqual(int[][] matrix, int val) {
        int res = 0;
        int n = matrix.length;
        int i = n - 1, j = 0;
        while (i >= 0 && j < n) {
            if (matrix[i][j] > val) i--;
            else {
                res += i + 1;
                j++;
            }
        }
        return res;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容