C/C++ 每日一练:在矩阵中查找特定值

本次练习将解决一个经典问题------在一个二维矩阵中查找特定的值。通过这个练习,可以更好地掌握二维数组的操作,以及优化算法的设计。


题目要求

给定一个二维矩阵 matrix,每行从左到右递增排序,每列从上到下递增排序,以及一个目标值 target。编写一个函数来判断目标值是否存在于矩阵中。如果存在,返回 true;否则,返回 false。

示例

cpp 复制代码
输入:
matrix = [
  [1, 4, 7, 11],
  [2, 5, 8, 12],
  [3, 6, 9, 16],
  [10, 13, 14, 17]
]
若target = 5,输出:true

若target = 20,输出:false

解题思路

观察特性

  • 每行从左到右递增,每列从上到下递增。
  • 如果选择右上角或左下角的元素作为起点,可以通过比较值和 target,决定移动方向。

算法设计

  • 从矩阵的右上角开始:
    • 如果当前值等于 target,返回 true。
    • 如果当前值大于 target,向左移动(减少列号)。
    • 如果当前值小于 target,向下移动(增加行号)。
  • 如果越界,则说明 target 不在矩阵中,返回 false。

时间复杂度分析

  • 最多需要遍历一行和一列,总体复杂度为 O(m + n),其中 m 和 n 分别为矩阵的行数和列数。

示例代码

C 实现

cpp 复制代码
#include <stdio.h>
#include <stdbool.h>

// 查找目标值是否存在于矩阵中
bool searchMatrix(int matrix[][4], int rows, int cols, int target) {
    int row = 0;            // 从第一行
    int col = cols - 1;     // 最后一列开始

    while (row < rows && col >= 0) 
    {
        if (matrix[row][col] == target) 
        {
            return true;    // 找到目标值
        } else if (matrix[row][col] > target) {
            col--;          // 当前值大于目标值,向左移动
        } else {
            row++;          // 当前值小于目标值,向下移动
        }
    }
    return false;           // 遍历结束未找到目标值
}

int main() 
{
    int matrix[4][4] = {
        {1, 4, 7, 11},
        {2, 5, 8, 12},
        {3, 6, 9, 16},
        {10, 13, 14, 17}
    };
    int target = 5;

    if (searchMatrix(matrix, 4, 4, target)) {
        printf("Target %d found in the matrix.\n", target);
    } else {
        printf("Target %d not found in the matrix.\n", target);
    }

    return 0;
}

C++ 实现

cpp 复制代码
#include <iostream>
#include <vector>

using namespace std;

// 查找目标值是否存在于矩阵中
bool searchMatrix(vector<vector<int>>& matrix, int target) {
    int rows = matrix.size();           // 矩阵的行数
    int cols = matrix[0].size();        // 矩阵的列数
    int row = 0;                        // 从第一行
    int col = cols - 1;                 // 最后一列开始

    while (row < rows && col >= 0) 
    {
        if (matrix[row][col] == target) {
            return true;                // 找到目标值
        } else if (matrix[row][col] > target) {
            col--;                      // 当前值大于目标值,向左移动
        } else {
            row++;                      // 当前值小于目标值,向下移动
        }
    }
    return false;                       // 遍历结束未找到目标值
}

int main() 
{
    vector<vector<int>> matrix = {
        {1, 4, 7, 11},
        {2, 5, 8, 12},
        {3, 6, 9, 16},
        {10, 13, 14, 17}
    };
    int target = 5;

    if (searchMatrix(matrix, target)) {
        cout << "Target " << target << " found in the matrix." << endl;
    } else {
        cout << "Target " << target << " not found in the matrix." << endl;
    }

    return 0;
}
相关推荐
遥感知识服务12 分钟前
从局部阈值、双极化到暗地表剔除:NASA OPERA DSWx-S1全球动态水体算法拆解
大数据·人工智能·深度学习·神经网络·算法·机器学习
晚风醉蝶18 分钟前
1-13-TimSort
算法
ZJU_统一阿萨姆27 分钟前
【算子开发】算子融合与Softmax_LayerNorm实现
人工智能·算法·语言模型·硬件架构
小小龙学IT2 小时前
FlatBuffers 深度解析:Google 开源零拷贝序列化库完全指南
c++·开源
叩码以求索2 小时前
浅谈:前序遍历反转法求解N叉树的后序遍历
算法
wuminyu3 小时前
JDK21中虚拟线程和FFM协同实现高并发源码剖析
java·linux·c语言·jvm·c++
SWAGGY..3 小时前
【C++进阶】:(1)继承机制详解
java·jvm·c++
北风toto4 小时前
中缀、前缀、后缀表达式
算法·软件设计师
听取WA声一片(无恶意)4 小时前
CSP-J/CSP-S 深度优先搜索(DFS)完全讲义
c++·算法·深度优先
码匠许师傅4 小时前
【C++ 面试真题】27. 聊聊 C++ 的内存泄漏与内存布局
java·c++·面试