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;
}
相关推荐
计算机小白一个2 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
万事可爱^3 小时前
HDBSCAN:密度自适应的层次聚类算法解析与实践
算法·机器学习·数据挖掘·聚类·hdbscan
黑不溜秋的3 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
李白同学3 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
楼台的春风5 小时前
【MCU驱动开发概述】
c语言·驱动开发·单片机·嵌入式硬件·mcu·自动驾驶·嵌入式
大数据追光猿5 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!5 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉5 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生5 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴5 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯