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;
    }
};
相关推荐
吞下星星的少年·-·1 分钟前
牛客技能树:区间翻转
算法·滑动窗口
拂拉氏1 小时前
【知识讲解】 链式哈希表的实现与unordered_map和unordered_set的封装
数据结构·哈希算法·散列表
haolin123.1 小时前
数据结构--二叉树
数据结构
tkevinjd1 小时前
力扣148-排序链表
算法·leetcode·链表
不如语冰1 小时前
AI大模型入门-参数的传递
数据结构·人工智能·pytorch·python
qeen871 小时前
【C++】vector的模拟实现详解(二)
c++·学习·算法·迭代器·stl
流浪0012 小时前
数据结构篇(四):线性表——链表——双链表
数据结构·链表
小七在进步2 小时前
数据结构:堆排序
数据结构
沉迷学习 日益消瘦3 小时前
4 净资产趋势可视化:SVG 图表 + 手势交互 + 降采样算法
算法·交互
可编程芯片开发14 小时前
基于MATLAB的PEF湍流风场生成器模拟与仿真
算法