您的位置:首页 > 编程语言

编程练习--二维数组的查找

2016-07-05 22:02 190 查看
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

输入描述:

array: 待查找的二维数组

target:查找的数字

输出描述:

查找到返回true,查找不到返回false

—– 牛客编程题(剑指offer)

1. 思路一

从第一行第一列从左往右逐个对比,到了行尾仍没有则另起一行,列数置0。这个方法算是遍历对比,效率较低。

代码如下:

class Solution
{
public:
bool Find(vector<vector<int> > array,int target)
{
int rows;
int columns;
rows = array.size();        // 数组的总行数
columns = array[0].size();  // 数组的总列数
int row = 0;                // 第一行
int column = 0;             // 第一列
bool found = false;         // 默认未找到
while( row < rows && column < columns )   // 查找方法为从第一行开始,从左往右挨个对比。
{
if( array[row][column] == target )
{
found = true;
break;
}
else if( array[row][column] < target )
{
++column;
if (column == columns)
{
column = 0;
++row;
}

}
else
{ ++row;
column=0;
}
}
return found;
}
};


2.思路二

从第一行的尾部开始,倒序对比,只有当前数字比target大,才将当前数字位置前移,因为每一行都是递增的,若当前数字比target小,那么当前数字之前的数字肯定比target小,没有比的必要,从而继续比对下一行。

代码如下:

class Solution {
public:
bool Find(vector<vector<int> > array,int target) {
int row, col ,i ,j ;
row = array.size();
col = array[0].size();
i = 0;
j = col -1;
while(i < row && j >= 0)
{
if( array[i][j] == target)
{
return true;
}
else if(array[i][j] > target)
--j;
else
++i;
}
return false;
}
};


3.思路三(最佳思路)

矩阵是有序的,从左下角来看,向上数字递减,向右数字递增,因此从左下角开始查找,当要查找数字比左下角数字大时。右移要查找数字比左下角数字小时,上移。

代码如下:

class Solution
{
public:
bool Find(vector<vector<int> > array,int target)
{
int rowCount = array.size();
int colCount = array[0].size();
int i,j;
for(i=rowCount-1,j=0;i>=0&&j<colCount;)
{
if(target == array[i][j])
return true;
if(target < array[i][j])
{
i--;
continue;
}
if(target > array[i][j])
{
j++;
continue;
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二维数组 编程