LEETCODE刷题 二维数组查找

//给定一个二维数组,其每一行从左到右递增排序,从上到下也是递增排序。给定一个数,判断这个数是否在该二维数组中。
//要求时间复杂度 O(M + N),空间复杂度 O(1)。其中 M 为行数,N 为 列数。
//该二维数组中的一个数,小于它的数一定在其左边,大于它的数一定在其下边。因此,从右上角开始查找,就可以根据 target 
//和当前元素的大小关系来缩小查找区间,当前元素的查找区间为左下角的所有元素。
#include<stdio.h>
int  Find(int target, int matrix[3][3],int rows,int cols) 
{
    //判空
    
    int r = 0, c = cols - 1; // 从右上角开始
    while (r <= rows - 1 && c >= 0)
    {
        if (target == matrix[r][c])
        {
            return 1;
        }
        else if (target > matrix[r][c])  //以右上角的数作为基准,大于当前数,一定在其下面,小于当前数一定在其左边
        {
            r++;
        }
        else
        {
            c--;
        }
    }
    return 0;
}
int main(void)
{
    int a[3][3] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
    int target = 9;
    int row = 3;
    int col = 3;
    int ret = Find(target,a,row,col);
    if(ret == 1)
    {
        printf("find
");
    }
    else
    {
        printf("not find 
");
    }
}
原文地址:https://www.cnblogs.com/anitaguangzi/p/13197621.html