查找类问题是一个非常常见的任务。无论是从简单的数组中查找一个特定的数字,还是从复杂的数据结构中检索信息,查找算法的效率和正确性都十分重要。今天,我们将探讨一个有趣的查找问题:在不完全递增序的矩阵中查找特定的元素。
假设我们有一个二维矩阵,矩阵的每一行从左到右是递增的,但列与列之间并没有严格的递增关系。这种矩阵被称为“不完全递增序矩阵”。
例如,以下矩阵满足这一条件 13572468101112139141516
在这个矩阵中,每一行都是递增的,但列与列之间并不完全递增。
给定一个不完全递增序的矩阵和一个目标数字,编写一个程序来判断该数字是否存在于矩阵中。 假设矩阵如下,而且目标数字为 12:
1 | 3 | 5 | 7 |
|---|---|---|---|
2 | 4 | 6 | 8 |
10 | 11 | 12 | 13 |
9 | 14 | 15 | 16 |
此时,程序返回 true。
优化查找算法。虽然列与列之间没有严格的递增关系,但行的递增性仍然可以为我们提供一些线索。我们在接下来的文章中会利用这一点解题。最简单的查找方法是暴力搜索,即遍历矩阵的每一个元素,检查是否等于目标值。这种方法的时间复杂度为 O(M×N),效率较低。
#include <stdio.h>
#include <stdbool.h>
#define M 4
#define N 4
//暴力查找函数
bool find_brute_force(int matrix[M][N], int target) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (matrix[i][j] == target) {
return true;
}
}
}
return false;
}
//主函数
int main() {
//定义数组
int matrix[M][N] = {
{1, 3, 5, 7},
{2, 4, 6, 8},
{10, 11, 12, 13},
{9, 14, 15, 16}
};
int target = 12;
//查找与输出
if (find_brute_force(matrix, target)) {
printf("Target %d found in the matrix.\n", target);
} else {
printf("Target %d not found in the matrix.\n", target);
}
return 0;
}运行结果如下:

虽然矩阵的列没有严格的递增关系,但每一行的递增性可以被利用。我们可以对每一行进行二分查找。这种方法的时间复杂度为 O(MlogN)。
#include <stdio.h>
#include <stdbool.h>
#define M 4
#define N 4
bool binary_search(int arr[], int target) {
int left = 0, right = N - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return true;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
bool find_row_wise(int matrix[M][N], int target) {
for (int i = 0; i < M; i++) {
if (binary_search(matrix[i], target)) {
return true;
}
}
return false;
}
int main() {
int matrix[M][N] = {
{1, 3, 5, 7},
{2, 4, 6, 8},
{10, 11, 12, 13},
{9, 14, 15, 16}
};
int target = 12;
if (find_row_wise(matrix, target)) {
printf("Target %d found in the matrix.\n", target);
} else {
printf("Target %d not found in the matrix.\n", target);
}
return 0;
}运行结果如下:

通过分析条件的特性,选择合适的查找算法和数据结构,是程序员的重要素质。对于这道题,即不完全递增序的矩阵,逐行二分查找是一种有效的优化策略。
关注窝,每三天至少更新一篇优质c语言题目详解~