#include <iostream>
using namespace std;
// 从右上角开始
bool Find(const int* matrix, const int &rows, const int &columns, const int &number) {
bool found = false;
if (matrix != NULL && rows > 0 && columns > 0) {
int row = 0;
int column = columns - 1;
while (row < rows && column >= 0) {
// 思想:要么往下,要么往左,所以一个循环就可以了。
if (matrix[row * columns + column] == number) {
found = true;
cout << "(" << row << "," << column << ")" << endl;
break;
}
else if (matrix[row * columns + column] > number){
column--;
}
else {
row++;
}
}
}
return found;
}
// 从左下角开始
bool Find2(const int* matrix, const int &rows, const int &columns, const int &number) {
bool found = false;
if (matrix != NULL && rows > 0 && columns > 0){
int row = rows - 1;
int column = 0;
while (row >= 0 && column < columns) {
if (matrix[row * columns + column] == number) {
found = true;
cout << "(" << row << "," << column << ")" << endl;
break;
}
else if (matrix[row * columns + column] > number) {
row--;
}
else {
column++;
}
}
}
return found;
}
int main() {
// 算法
int matrix[] = { 1,2,8,9,
2,4,9,12,
4,7,10,13,
6,8,11,15 };
bool ret;
ret = Find2(matrix, 4,4,5);
cout << ret << endl;
system("pause");
return 0;
}
4 二维数组中的查找
最新推荐文章于 2021-03-18 01:43:25 发布