一、在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
1、用C++实现:;
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
// array是二维数组,这里没做判空操作
int rows = array.size();
int cols = array[0].size();
int i=rows-1,j=0;//左下角元素坐标
while(i>=0 && j<cols){//使其不超出数组范围
if(target<array[i][j])
i--;//查找的元素较少,往上找
else if(target>array[i][j])
j++;//查找元素较大,往右找
else
return true;//找到
}
}
};
报错:./solution.h:23:5: error: control may reach end of non-void function [-Werror,-Wreturn-type]
原因:漏写了错误的返回值:return false;
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int i=array.size();
int j=array[0].size();
int x=i-1;
int y=0;
while(x>=0&&y<j)
{
if(target>array[x][y])
{
y++;
continue;
}
else if(target<array[x][y])
{
x--;
continue;
}
else
return true;
}
return false;
}
};
2、用C语言实现,以下过程,无论输入什么数字都会输出“没有找到”,原因是:
# define _CRT_SECURE_NO_WARNINGS 1
# include<stdio.h>
# include<stdlib.h>
# include<string.h>
# include<assert.h>
//在一个二维数组中(每个一维数组的长度相同),
//每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
//请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
# define Row 3
# define Col 3
int Find(int arr[Row][Col], int k)
{
int i = Row-1;
int j = 0;
while (i >=0&&j <Col)
{
if (k>arr[i][j])
{
j ++;
}
else if (k < arr[i][j])
{
i --;
}
else
return 1;
}
return 0;
}
int main()
{
int arr[Row][Col] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
int key = 0;
scanf("%d", &key);
if (Find(arr[Row][Col], key))
printf("找到了\n");
else
printf("没有找到\n");
system("pause");
return 0;
}