[每日练习] write a function to find the key in a m*n matrix, where each line and column is incremental

本文介绍了一种在特殊排序的二维数组中查找特定整数的方法。该数组每行按从左到右递增排序,每列按从上到下递增排序。通过从右上角开始逐次排除行列的方式高效查找目标值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

解题思路:从二维数组的右上角的元素开始判断,因为此元素是它所在行的最大数,是它所在的列的最小数。如果它等于要查找的数字,则查找过程结束。如果它大于要查找的数字,则可以排除它所在的列。如果它小于要查找的数字,则可排除它所在的行。这样如果要查找的数字不在数组的右上角,则每次判断都可以排除一行或一列以缩小查找范围,直到找到要查找的数字,或者查找范围为空。

下图是在二维数组中查找7的示意图:

参考代码:

#include 

int find_in_ordered_2_dimension_array(int *arr, int line_num, int column_num, int key)
{
	int found = 0, ret_line = -1, ret_column = -1;
	int i = 0, j = column_num - 1;
	int current_idx;

	while (i=0)
	{
		current_idx = i*column_num + j;
		if (arr[current_idx] == key)
		{
			ret_line = i;
			ret_column = j;
			found = 1;
			break;
		}
		else if(arr[current_idx] > key)
		{
			j--;
		}
		else
		{
			i++;
		}
	}

	if (found == 1)
	{
		printf("%d has been found at [%d][%d]\n", key, ret_line, ret_column);
	}
	else
	{
		printf("%d not found\n", key);
	}
	
	return found;
}

int main()
{
	int a[4][4] = {{1,2,8,9}, {2,4,9,12}, {4,7,10,13}, {6,8,11,15}};
	int found = 0;

	printf("find-in-ordered-2-dimension-array begin\n");
	found = find_in_ordered_2_dimension_array((int *)a, 4, 4, 1);
	found = find_in_ordered_2_dimension_array((int *)a, 4, 4, 2);
	found = find_in_ordered_2_dimension_array((int *)a, 4, 4, 13);
	found = find_in_ordered_2_dimension_array((int *)a, 4, 4, 15);
	found = find_in_ordered_2_dimension_array((int *)a, 4, 4, 7);
	printf("find-in-ordered-2-dimension-array end\n");

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值