题目描述
有一个数字矩阵,矩阵的每行从左到右是递增的,矩阵从上到下是递增的,请编写程序在这样的矩阵中查找某个数字是否存在。
思路:
右上角的元素是一行中的最大元素,是一列中的最小的元素。如果目标元素比当前这行右上角元素大,则这一行都不满足。如果目标元素比当前这行右上角元素小,则这一列都不满足。
代码:
#include <stdio.h>
int main() {
int nums[3][3] = {
{1 , 2 , 3},
{4 , 5 , 6},
{7 , 8 , 9}
};
int target = 5;
int row = sizeof(nums) / sizeof(nums[0]);
int col = sizeof(nums[0]) / sizeof(nums[0][0]);
// 从第一行右上角开始
int x = 0;
int y = col - 1;
int flag = 0;
while (x < col && y >= 0) {
if (nums[x][y] < target) {
x++;
}
else if (nums[x][y] > target) {
y--;
}
else {
printf("找到了,下标:%d %d", x, y);
flag = 1;
break;
}
}
if (!flag) {
printf("找不到\n");
}
return 0;
}