401 · 排序矩阵中的从小到大第k个数

链接:LintCode 炼码 - ChatGPT!更高效的学习体验!

题解: 九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧

cpp 复制代码
class Solution {
public:
    /**
     * @param matrix: a matrix of integers
     * @param k: An integer
     * @return: the kth smallest number in the matrix
     */
class Node {
public:
    Node(int v, int i):val(v),index(i) {

    }
    bool operator < (const Node& node) const {
        return val > node.val ? true : false;
    }
    int val;
    int index;
};
    int kthSmallest(vector<vector<int>> &matrix, int k) {
        // write your code here
        int m = matrix.size();
        if (m <= 0) {
            return 0;
        }
        int n = matrix[0].size();
        if (n <= 0) {
            return 0;
        }
        std::vector<bool> distance(m*n, false);
        distance[0] = true;
        std::priority_queue<Node> que;
        que.push(Node(matrix[0][0], 0)); 
        int i = 1;
        std::vector<std::vector<int>> direction{{0, 1}, {1, 0}};
        while (!que.empty()) {
            auto f = que.top();
            que.pop();
            if (i >= k) {
                return f.val;
            }
            for (int j = 0; j < direction.size(); ++j) {
                int next_row = f.index / n + direction[j][0];
                int next_col = f.index % n + direction[j][1];
                if (next_row < 0 || next_col < 0 || next_row >= m || next_col >= n) {
                    continue;
                }
                int node = next_row * n + next_col;
                if (distance[node]) {
                    continue;
                }
                que.push(Node(matrix[next_row][next_col], node));
                distance[node] = true;
            }
            ++i;
        }
        return -1;
    }
};
相关推荐
labuladong1 小时前
机器学习&神经网络 系列教程上线
神经网络·算法·机器学习
xiangyun611 小时前
C++ 手撕 shared_ptr:引用计数与控制块到底长什么样?
开发语言·c++·算法·面试·stl
学习论之费曼学习法1 小时前
无人值守AI内容矩阵实战(8):标题 A/B 实验的 6 个工程实现细节,隔日对比与自动判胜
人工智能·python·算法·矩阵·自动化·a/b测试·内容矩阵
Carl_奕然1 小时前
【机器视觉】最强算法之:3D高斯泼溅(3D Gaussian Splatting)
人工智能·python·算法·目标检测·计算机视觉·3d
w_zero_one1 小时前
算法--桶思想
java·开发语言·算法
wordbaby2 小时前
同一次请求里的两道锁:图解搞懂国密 SM2 与 SM3
算法
miller-tsunami3 小时前
内存管理&模板
c++·算法·内存管理·模板
青少儿编程课堂3 小时前
蓝桥杯青少组·全国青少年信息素养·电子学会Scratch考级:校园智能抢答器项目解析
c++·python·算法·bfs·信息学竞赛
SZYSK3 小时前
一套人员主数据,三套事务:通行、消费、人证比对如何分事件类型
物联网·算法·harmonyos
怕浪猫4 小时前
不用摄像机,我把历史故事做成竖屏视频
算法·面试·github