Saturday, October 22, 2016

Kth Smallest Element in a Sorted Matrix

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.
Note: 
You may assume k is always valid, 1 ≤ k ≤ n2.


The best solution is to use binary search. Based on the nature of the matrix, we know the minimum of the matrix is its upper left element and the max is the lower right. Now we try to get the mid of the element and find the position of the mid in the matrix. If the position is less than k, we let left = mid + 1, otherwise right = mid.

Now how to find the position of the mid? We start from lower left element. If the element is smaller than target, we know all elements in current column is smaller than target, so we add pos by #row + 1. And we increment column by 1. Otherwise we decrease row by 1.


public int kthSmallest(int[][] matrix, int k) {
        if (matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        int r = matrix.length;
        int c = matrix[0].length;
        int left = matrix[0][0], right = matrix[r - 1][c - 1];
        while (left < right) {
            int mid = (left + right) / 2;
            int pos = getPos(matrix, mid);
            if (pos < k) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
    
    private int getPos(int[][] matrix, int target) {
        int r = matrix.length;
        int c = matrix[0].length;
        int pos = 0;
        for (int i = r - 1, j = 0; i >= 0 && j < c;) {
            if (matrix[i][j] <= target) {
                pos += i + 1;
                j++;
            } else {
                i--;
            }
        }
        return pos;
    }


1 comment:

  1. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. IEEE final year projects on machine learning In case you will succeed, you have to begin building machine learning projects in the near future.

    Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.


    Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

    ReplyDelete