楊氏矩陣(Young Tableau)是指每行左到右遞增、每列上到下遞增的二維數組。在這類矩陣中查找目標值,利用有序特性可達到 O(m+n) 時間複雜度,遠優於暴力 O(mn)。
從右上角(或左下角)開始:
每一步排除一行或一列,最多 m+n-1 步。
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int search_matrix(int *arr, int target, int rows, int cols) {
if (!arr || rows <= 0 || cols <= 0) return 0;
int row = 0;
int col = cols - 1; // 從右上角開始
while (row < rows && col >= 0) {
int current = arr[row * cols + col];
if (current == target) {
return 1; // 找到
} else if (current < target) {
row++; // 向下:當前行所有元素都小於 target
} else {
col--; // 向左:當前列所有元素都大於 target
}
}
return 0; // 未找到
}
int main() {
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int target = 7;
int found = search_matrix((int *)arr, target, 3, 3);
printf("%s\n", found ? "exist" : "not exist");
system("pause");
return 0;
}
arr[row * cols + col] 將二維邏輯映射到一維內存row < rows && col >= 0 確保不越界若矩陣允許重複值,需修改為繼續搜索並記錄所有位置,時間複雜度仍為 O(m+n+k)。