LeetCode 378. Kth Smallest Element in a Sorted Matrix

来源:互联网 发布:淘宝企业店铺开通流程 编辑:程序博客网 时间:2024/06/06 12:44

问题描述:

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.

Subscribe to see which companies asked this question.

思路:

之前写过一道类似的题,是搜索某个值,比较简单,这道题是搜索第k大的值,所以咋看起来很简单,但是解出来还是费了很多力气。因为没有限制复杂度,可以暴力排序,但是这样就没有意义了。后来参考了solution,有个二分查找的思路比较好:每次二分查找mid是第m大元素,如果m>k就在low-mid中查找,反之在mid-high中查找,不断循环mid=(low+high)/2,直到查找到m=k为止。其中中间的临界值的边界条件需要自习处理下,不然容易无限循环或者错过正确值。

代码:

class Solution {public:int kthSmallest(vector<vector<int>>& matrix, int k) {int n = matrix.size();int lo = matrix[0][0], hi = matrix[n - 1][n - 1];while (lo < hi) {int mid = (hi + lo) / 2;int c = 0;for (int i = 0; i < n; i++) {int j = 0;while (j < n && matrix[i][j] <= mid) j++;c += j;}if (c >= k) hi = mid;else lo = mid+1;}return lo;}};


阅读全文
0 0