如何使用C#在一个行级增加的矩阵中搜索?
解决此问题的原始方案是扫描存储在输入矩阵中的所有元素,以搜索给定的关键字。如果矩阵的大小为 MxN,则此线性搜索方法需要花费 O(MN) 时间。
需要从右上角扫描矩阵,如果搜索元素大于右上角元素,则增加行,否则减少列。以下代码片段开发了一个函数 SearchRowwiseIncrementedMatrix,该函数将一个二维数组和搜索关键字作为输入,并根据找到搜索关键字的成功或失败返回 true 或 false。
代码
public class Matrix{
public bool SearchRowwiseIncrementedMatrix(int[,] mat, int searchElement){
int row = getMatrixRowSize(mat);
int col = getMatrixColSize(mat) - 1;
int r = 0;
while (col >= 0 && r < row){
if (mat[r, col] == searchElement){
return true;
}
else if (searchElement < mat[r, col]){
col--;
}
else{
r++;
}
}
return false;
}
private int getMatrixRowSize(int[,] mat){
return mat.GetLength(0);
}
private int getMatrixColSize(int[,] mat){
return mat.GetLength(1);
}
}
static void Main(string[] args){
Matrix m = new Matrix();
int[,] mat = new int[3, 4] { { 1, 7, 10, 19 }, { 2, 8, 11, 20 }, { 3, 9, 12, 21 } };
Console.WriteLine(m.SearchRowwiseIncrementedMatrix(mat, 11));
}输出
TRUE
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP