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;
}

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

相关推荐
phltxy3 小时前
C语言操作符详解
java·c语言·算法
aqiu1111113 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye4 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考5 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾5 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研6 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a187927218317 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_962297487 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye8 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展