題目:在一個遞增二維數組中查找是否含有某元素
在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。
請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
思路:
1.
將二維數組傳入找到函數中
3.從二維數組傳入右上角的數字開始查找:
(1)若右上角數字== num,返回true,由於數組的遞增特性
(2)若右上角數字<num,則縮小範圍,跳過當前列(因爲當前列的數字是遞增的,不可能有數)
(3)若右上角數字> num,則跳過當前行(因爲右上角數字已經是第一行最大的數字,當第一行前面數字不可能比右上角更大)
圖片來自:http: //cuijiahua.com/blog/2017/11/basis_1.html感謝這位博主,劍指提供都是跟着他刷的
C語言實現
#include<iostream>
using namespace std;
bool FindNumInArray(int **arr,int num,int col,int row)
{
int _row=0;
int _col=col-1;
while(_row<row &&_col <col)
{
if(arr[_row][_col]==num)
{
cout<<"find"<<endl;
return true;
}
else if(arr[_row][_col]<num)
{
_row++;
}
else if(arr[_row][_col]>num)
{
_col--;
}
}
cout<<"can not find"<<endl;
return false;
}
int main()
{
int **p;
int row;
int col;
cin>>row>>col;
p=new int* [row];
for(int i=0;i<row;i++)
{
p[i]=new int[col];
for(int j =0;j<col;j++)
{
cin>>p[i][j];
}
}
FindNumInArray(p,2,col,row);
system("pause");
return 0;
}
C++實現
class solution
{
public:
bool find(int num,vector<vector<int>> arr)
{
int row = arr.size();
int col = arr[0].size();
if(!arr.empty() && row>0 && col>0)
{
int rows = 0;
int cols=col-1;
while(rows<row && cols>0)
if(arr[rows][cols] == num)
{
cout<<"find it"<<endl;
return true;
}
else if (arr[rows][cols]<num)
{
++rows;
}
else
{
--cols;
}
}
cout<<"can not find "<<endl;
return false;
}
};
int main()
{
solution a;
vector< vector<int> > arr(3);
for(int i =0;i<3;i++)
{
arr[i].resize(3);
}
cout<<"please in put the arr "<<endl;
for (int i = 0; i < 3; i++)
{
for(int j =0;j<3;j++)
{
cin>>arr[i][j];
cout<<arr[i][j]<<" ";
}
putchar(10);
}
cout<<"please input the find num"<<endl;
int num;
cin>>num;
a.find(num,arr);
system("pause");
return 0;
}