本文最后更新于:2020年6月27日 晚上

题目描述:

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

实现如下:

/*
1 2 8  9
2 4 9  12
4 7 10 13
6 8 11 15
*/

//从右上角或左下角突破,时间复杂度O(n)
class Solution
{
public:
	bool Find(int target, vector<vector<int>> array)
	{
		if (array.empty()) return false;//为空结束
		//获取行、列数
		int row = array.size();
		int col = array[0].size();
		
		int i = 0;
		int j = col - 1;
		while ((i >= 0 && i < row) && (j >= 0 && j < col))//防止越界
		{
			//说明array[i][y]此行右边和此列下方的数都大于target
			if (array[i][j] > target)	--j;
			//找到返回true
			else if (array[i][j] == target) return true;
			//说明array[i][j]此行左边的数和此列上方的数都小于target
			else	++i;
		}
		return false;//没找到返回false
	}
};