剑指offer(三):二维数组中的查找 递增数组 C 和C++实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39087263/article/details/83022641

题目:在一个递增二维数组中查找是否含有某元素

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

思路:

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;
}

猜你喜欢

转载自blog.csdn.net/weixin_39087263/article/details/83022641