每日两题 / 240. 搜索二维矩阵 II && 48. 旋转图像 - 力扣(LeetCode热题100)

240. 搜索二维矩阵 II - 力扣(LeetCode)

从右上角开始搜索,若当前值大于target,向左走,因为当前列的所有值都大于target

若当前值小于target,则当前行向左的所有值小于target,向下走

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

48. 旋转图像 - 力扣(LeetCode)

讲一个符合我直觉的解法:从外向内,一层层地旋转

每次完成一层中4个数的位置交换,如何得到这4个数的坐标?

每次坐标的变化,方向都是固定的:右下左上

并且每次的曼哈顿距离都是相同的

加上每次向一个方向移动k个曼哈顿距离,但是移动后的坐标"出界",此时就要向另一个方向调整

将出界的曼哈顿距离加到另一个方向上

cpp 复制代码
class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size(), m = matrix[0].size();
        int dx[4] = { 0, 1, 0, -1 }, dy[4] = { 1, 0, -1, 0 };
        int l = 0, r = m - 1, u = 0, d = n - 1;
        int len = m - 1;
        for (int i = 0; i < n / 2; ++ i)
        {
            for (int j = i; j < m - i - 1; ++ j)
            {
                int x = i, y = j;
                int next, cur = matrix[x][y];
                for (int k = 0; k < 4; ++ k)
                {
                    int nx = x + len * dx[k], ny = y + len * dy[k];
                    if (ny > r)
                    {
                        nx += (ny - r);
                        ny = r;
                    }
                    else if (nx > d)
                    {
                        ny -= (nx - d);
                        nx = d;
                    }
                    else if (ny < l)
                    {
                        nx -= (l - ny);
                        ny = l;
                    }
                    else if (nx < u)
                    {
                        ny += (u - nx);
                        nx = u;
                    }
                    x = nx, y = ny;
                    next = matrix[nx][ny];
                    matrix[nx][ny] = cur;
                    cur = next;
                }

            }
            l ++ , r --, u ++ , d -- ;
            len -= 2;
        }
    }
};

// 右下左上
// j+, i+
// i+, j-
// j-, i+
// i-, j+
相关推荐
旖旎夜光4 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
CoderYanger4 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂4 天前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Tim_104 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
微三云 - 廖会灵 (私域系统开发)4 天前
企业大模型应用工程化思考:跳出 Demo 陷阱,构建「业务‑资产‑Agent」三层落地架构
人工智能·矩阵·重构
tryxr5 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_35 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z5 天前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.5 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好5 天前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法