C++ | Leetcode C++题解之第378题有序矩阵中第K小的元素

题目:

题解:

cpp 复制代码
class Solution {
public:
    bool check(vector<vector<int>>& matrix, int mid, int k, int n) {
        int i = n - 1;
        int j = 0;
        int num = 0;
        while (i >= 0 && j < n) {
            if (matrix[i][j] <= mid) {
                num += i + 1;
                j++;
            } else {
                i--;
            }
        }
        return num >= k;
    }

    int kthSmallest(vector<vector<int>>& matrix, int k) {
        int n = matrix.size();
        int left = matrix[0][0];
        int right = matrix[n - 1][n - 1];
        while (left < right) {
            int mid = left + ((right - left) >> 1);
            if (check(matrix, mid, k, n)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
};
相关推荐
小白菜又菜1 天前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
wuhen_n1 天前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo1 天前
leetcode 2483
数据结构·算法·leetcode
阿闽ooo1 天前
外观模式:从家庭电源控制看“简化接口“的设计智慧
c++·设计模式·外观模式
你的冰西瓜1 天前
C++中的list容器详解
开发语言·c++·stl·list
wuhen_n1 天前
LeetCode -- 1:两数之和(简单)
javascript·算法·leetcode·职场和发展
Jeremy爱编码1 天前
leetcode课程表
算法·leetcode·职场和发展
努力学算法的蒟蒻1 天前
day46(12.27)——leetcode面试经典150
算法·leetcode·面试
CC.GG1 天前
【C++】哈希表的实现
java·c++·散列表
元亓亓亓1 天前
LeetCode热题100--152. 乘积最大子数组--中等
算法·leetcode·职场和发展