您的位置:首页 > 其它

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

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

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

下图是在二维数组中查找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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐