LeetCode74.搜索二维矩阵

各位客官们,大家好,今天我将给大家讲一个关于二维搜索矩阵的简单方法,大家如果觉得好的话不妨给个免费点赞吧^ _ ^.

题目要求,如图所示:

此题我用的是堆的形式直接把二维数组转为一级数组,然后再用二分查找的方式,就能直接判别目标值了,代码如图所示:

c 复制代码
int Binary_search(int* arr,int length,int target)
{
    int left = 0;
    int right = length - 1;
    while(left <= right)
    {
        int mid = (left + right) / 2;
        if(arr[mid] == target)
        {
            return 1;
        }else if(target > arr[mid]){
            left = mid + 1;
        }else{
            right = mid - 1;
        }
    }
    return 0;
}
bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target) {
    int col = *matrixColSize;
    int total = matrixSize * col;
    int* arr = (int*)malloc(sizeof(int) * total);
    int len = 0;
    int i = 0;
    int j = 0;
    for(i = 0;i < matrixSize;i++)
    {
        for(j = 0;j < col;j++)
        {
            arr[len] = matrix[i][j];
            len++;
        }
    }
    int ret = Binary_search(arr,len,target);
    if(ret == 1)
        return true;
    else
        return false;
}

好了,这就是我的代码,如果大家觉得好的话,不妨给个免费的赞吧 ^ _ ^.

相关推荐
luckys.one2 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|3 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师4 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo34 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
阿巴Jun4 小时前
【数学】线性代数知识点总结
笔记·线性代数·矩阵
好家伙VCC5 小时前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
liulilittle6 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
bkspiderx8 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐9 小时前
算法之常见八大排序
数据结构·算法·排序算法
沐怡旸9 小时前
【算法--链表】114.二叉树展开为链表--通俗讲解
算法·面试