力扣hot100——矩阵

73. 矩阵置零

cpp 复制代码
class Solution {
public:
    void setZeroes(vector<vector<int>>& a) {
        int n = a.size(), m = a[0].size();
        vector<int> r(n + 10, 0);
        vector<int> c(m + 10, 0);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (!a[i][j]) {
                    r[i] = 1;
                    c[j] = 1;
                }
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (r[i] || c[j]) a[i][j] = 0;
            }
        }
    }
};

模拟

54. 螺旋矩阵

cpp 复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& a) {
        int n = a.size(), m = a[0].size();
        int x = 0, y = 0;
        int sum = m * n;

        int sx = n - 1, sy = m;
        int dx = 1, dy = 1;
        vector<int> ans;
        while (sum) {
            for (int i = 1; i <= sy; i++) {
                ans.push_back(a[x][y]);
                y += dy;
                sum--;
            }
            dy *= -1;
            sy--;
            x += dx;
            y += dy;
            for (int i = 1; i <= sx; i++) {
                ans.push_back(a[x][y]);
                x += dx;
                sum--;
            }
            dx *= -1;
            sx--;
            y += dy;
            x += dx;
        }
        return ans;
    }
};

套路题,模拟

48. 旋转图像

cpp 复制代码
class Solution {
public:
    void rotate(vector<vector<int>>& a) {
        int n = a.size(), m = a[0].size();
        vector<vector<int>> ans(n, vector<int>(m, 0));
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                ans[j][n - i - 1] = a[i][j];
            }
        }
        swap(a, ans);
    }
};

套路题,模拟

240. 搜索二维矩阵 II

cpp 复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& a, int target) {
        int n = a.size(), m = a[0].size();
        int x = 0, y = m - 1;
        while (x < n && y >= 0) {
            if (a[x][y] == target) return true;
            if (a[x][y] > target) y--;
            else x++;
        }
        return false;
    }
};

Z字形查找

相关推荐
开开心心就好1 小时前
电脑禁止自动休眠工具,还能按负载定时
算法·智能手机·pdf·电脑·word·音视频·lua
geovindu13 小时前
python:DecisionTree
开发语言·后端·python·算法
geovindu14 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
AllData公司负责人16 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康17 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
夜不会漫长18 小时前
C++:C++11特性
开发语言·c++·算法
秋天的怀念_David19 小时前
算法一千零一夜 · 第三十七夜 · 类型的过路费
java·程序人生·算法
xckkcxxck21 小时前
Kaggle S6E10 冠军方案精读(二):245 个模型的合唱团,和一个只会“线性指挥“的老师
算法
饮水桶_T1 天前
Git笔记
开发语言·笔记·算法