杨氏矩阵问题
问题描述:
-
杨氏矩阵定义:同行元素从左向右依次递增,同列元素从上到下依次递增,注意:杨氏矩阵行列数可以不相等
-
杨氏矩阵举例:
1 2 3 4 5 6 7 8 9 -
在杨氏矩阵中查找一个元素key,要求时间复杂度小于O(n)
解题思路:
-
我们关注的焦点在于杨氏矩阵右上角的元素(或左下角的元素)
-
以杨氏矩阵右上角的元素为例,去上图所示的矩阵
-
如果key大于右上角的元素则可以消掉一行,如果key小于右上角的元素则可以消掉一列
-
假设key=7,查找流程如下:
-
key>3,消掉第一行
-
----- ----- ----- 4 5 6 7 8 9 -
key>6,消掉第二行
-
----- ----- ----- ----- ----- ----- 7 8 9 -
key<9,消掉第三列
----- ----- ----- ----- ----- ----- 7 8 ---- -
key<8,消掉第二列
-
----- ----- ----- ----- ----- ----- 7 ---- ---- -
找到了key,坐标为第三行,第一列
-
代码实现
#define _CRT_SECURE_NO_WARNINGS 1#include<stdio.h>
#include<string.h>
#include<assert.h>
int findNum(int arr[3][3],int key, int* row, int* col)
{int m = 0;int n = *col - 1;while (m<*row&&n>=0){if (key < arr[m][n]){n--;}else if (key > arr[m][n]){m++;}else{*row = m;*col = n;return 1;}}return 0;
}int main()
{int arr[3][3] = { {1,2,3},{4,5,6},{7,8,9} };int key = 7;int row = 3;int col = 3;//返回形参数int ret=findNum(arr, key, &row, &col);if (ret == 1){printf("找到了%d,该元素的位置为%d行, %d列",key, row+1, col+1);}else{printf("对不起您查找的元素不存在");}
}