Header Ad

Leetcode Kth Smallest Element in a Sorted Matrix problem solution

In this Leetcode Kth Smallest Element in a Sorted Matrix problem solution, we have given an n x n matrix where each of the rows and columns are sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Leetcode Kth Smallest Element in a Sorted Matrix problem solution


Problem solution in Python.

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        if not matrix:
            return 0
        for i in matrix[1:]:
            matrix[0] += i
        return sorted(matrix[0])[k - 1]



Problem solution in Java.

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>(Collections.reverseOrder());
        
        for(int i=0; i<matrix.length; i++) {
            for(int j = 0; j<matrix[i].length; j++) {
                if(queue.size() == k && queue.peek() > matrix[i][j]) queue.poll();
                if(queue.size() < k) queue.offer(matrix[i][j]);
            }
        }
        return queue.peek();
                                                  
    }
}


Problem solution in C++.

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        priority_queue<int,vector<int>,  
                       greater<int>>pq;
        for(auto i : matrix){
            for(auto x: i){
                pq.push(x);
            }
        }
        k = k-1;
        while(k--){
            pq.pop();
        }
        return pq.top();
    }
};


Problem solution in C.

int kthSmallest(int** matrix, int n, int useless, int k) {
    int small=matrix[0][0], big=matrix[n-1][n-1], mid, cnt, i, j;
    while(small<big) {
        mid=small+big>>1;
        cnt=0;
        j=n-1;
        for(i=0;i<n;i++) {
            while(j>=0&&matrix[i][j]>mid) --j;
            cnt+=j+1;
        }
        if(cnt<k) small=mid+1;
        else big=mid;
    }
    return big;
}


Post a Comment

0 Comments