题目:
在一个二维数组中,每一行都按照从左到右递增排序,每一列都按照从上到下递增排序输入这样一个二维数组和一个整数,判断这个整数在不在这个二维数组中
如果在返回true,如果不在返回false
例如矩阵:
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
这是一个4X4的矩阵,这个矩阵从上到下从左到右数据都是递增的,如果在这个矩阵中查找7,则返回true,查找14返回false
最先看到这个题的时候,总是往在0(n)时间复杂度的前提下找数组的中位数的题目,如果使用那种思想的话,会把问题弄的很复杂而无从下手。分析完一步之后就不知道该怎么继续往下分析了。
我们不妨换一种思路去考虑这个问题,我们可以从矩阵的右上角或者是左下角开始和要查找的数字进行比较,每比较一次就可以排除一行或者一列。最后的情况也是行数加列数次比较,时间复杂度为o(行数+列数)
实现代码如下:
#include <iostream>
using namespace std;
/*剑指offer,面试题三
*在一个二维数组中,每一行都按照从左到右递增排序,每一列都按照从上到下递增排序
*输入这样一个二维数组和一个整数,判断这个整数在不在这个二维数组中
*/
bool Find(int *matrix, int rows, int columns, int number )
{
bool found = false;
if(matrix!=NULL && rows>0 && columns>0)
{
int row = 0;
int column = columns-1;
while((row!=rows) && (column!=-1))
{
if(matrix[row*columns+column] == number)
{
found = true;
break;
}
else if(matrix[row*columns+column] > number)
{
--column;
}
else
{
++row;
}
}
}
return found;
}
// ==========================测试代码==================
void Test(char* testName, int* matrix, int rows, int colunms, int number, bool expected)
{
if(testName != NULL)
{
cout<<testName<<" begind:";
}
bool result = Find(matrix,rows,colunms,number);
if(result == expected)
{
cout<<"Passed"<<endl;
}
else
{
cout<<"Failed"<<endl;
}
}
/* 1 2 8 9
* 2 4 9 12
* 4 7 10 13
* 6 8 11 15
* 要查找的数在数组中的情况
*/
void Test1()
{
int matrix[][4] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
Test("Test1", (int *)matrix, 4, 4, 7, true);
}
/* 1 2 8 9
* 2 4 9 12
* 4 7 10 13
* 6 8 11 15
* 要查找的数不在数组中的情况
*/
void Test2()
{
int matrix[][4] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
Test("Test2", (int *)matrix, 4, 4, 14, false);
}
/* 1 2 8 9
* 2 4 9 12
* 4 7 10 13
* 6 8 11 15
* 要查找的数是数组中的最小值
*/
void Test3()
{
int matrix[][4] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
Test("Test3", (int *)matrix, 4, 4, 1, true);
}
/* 1 2 8 9
* 2 4 9 12
* 4 7 10 13
* 6 8 11 15
* 要查找的数是数组中的最大值
*/
void Test4()
{
int matrix[][4] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
Test("Test4", (int *)matrix, 4, 4, 15, true);
}
/* 1 2 8 9
* 2 4 9 12
* 4 7 10 13
* 6 8 11 15
* 要查找的数比最小值还小
*/
void Test5()
{
int matrix[][4] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
Test("Test5", (int *)matrix, 4, 4, 0, false);
}
/* 1 2 8 9
* 2 4 9 12
* 4 7 10 13
* 6 8 11 15
* 要查找的数比最大值还大
*/
void Test6()
{
int matrix[][4] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
Test("Test6", (int *)matrix, 4, 4, 20, false);
}
/*
* 输入NULL
*/
void Test7()
{
Test("Test7", NULL, 4, 4, 7,false);
}
int main()
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
return 0;
}
测试用例没有想到作者给的这么多,借鉴的作者的测试。以上代码有几点需要注意的地方
(1)首先就是讲二维数组当做函数的参数传递应该怎么传递
这里是将二维数组转化为了一维数组进行操作
关于二维数组做函数参数的情况见下面的代码:
#include <iostream>
using namespace std;
//测试二维数组当函数参数时的传递
void Test1(int *matrix)
{
cout<<"按照一维数组"<<matrix[10]<<endl;
}
void Test2(int matrix[][4])
{
cout<<"按照二维数组"<<matrix[2][2]<<endl;
}
int main()
{
int matrix[][4] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
Test1((int *)matrix);
Test2(matrix);
}
(2)这种测试的代码是模仿作者写的,感觉这种风格特别的好,以后要多多借鉴。