有一个数字矩阵,矩阵的每行从左到右是递增的,矩阵从上到下是递增的,请编写程序在这样的矩阵中查找某个数字是否存在。

2023年5月7日13:08:22

要求:时间复杂度小于O(N)

void find_k(int arr[3][3], int k, int r, int c)
{
	int x = 0;
	int y = c - 1;
	while (x<r && y>=0) {
		if (arr[x][y] < k)
		{
			x++;
		}
		else if (arr[x][y] > k)
		{
			y--;
		}
		else
		{
			printf("找到了,下标是:%d %d\n", x, y);
			return;
		}
	}
	printf("找不到\n");
}
int main()
{


	int arr[3][3] = {1,2,3,4,5,6,7,8,9};
	int k = 3;
	find_k(arr, k, 3, 3);
	return 0;


}

  • 作者:小孙的代码分享
  • 原文链接:https://blog.csdn.net/weixin_53939785/article/details/123656248
    更新时间:2023年5月7日13:08:22 ,共 270 字。