Duikerdd

杨氏矩阵
有一个二维数组.
数组的每行从左到右是递增的,每列从上到下是递增的.
在这样的数组中查找一个数字是否存在。
时间复杂度小于O(N);
数组:
1 2 3
2 3 4
3 4 5

1 3 4
2 4 5
4 5 6

1 2 3

4 5 6

7 8 9

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int find(int arr[3][3], int rows, int cols, int data)
{
    int i = 0;
    int j = cols - 1;
    while ((rows>i) && (j>0))
    {
        if (arr[i][j] > data)
        {
            j--;
        }
        else if (arr[i][j] < data)
        {
            i++;
        }
        else
        {
            return 1;
        }
    }
    return 0;
}
int main()
{
    int arr[3][3] = { { 1, 4, 7 }, { 4, 5, 8 }, { 7, 11, 12 } };
    int data = 0;
    printf("please input a number: ");
    scanf("%d", &data);

    int be_exist = find(arr, 3, 3, data);

    if (be_exist)
    {
        printf("%d is exist\n", data);
    }
    else
    {
        printf("%d is not exist\n", data);
    }
    system("pause");
    return 0;
}

 

分类:

技术点:

相关文章:

  • 2021-12-08
  • 2021-04-20
  • 2021-06-26
  • 2021-12-26
  • 2021-10-11
  • 2021-11-29
  • 2022-12-23
猜你喜欢
  • 2021-04-15
  • 2023-02-01
  • 2021-08-09
  • 2023-02-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案