剑指offer 题目1

130 阅读1分钟

题目描述

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

大致思路

  • 完全遍历的话就也不是不可以,因为只用遍历一次,但是有点 low 了吧。因为有序,首先我想到的是折半查找。
  • 二维数组是两个方向同时递增的,所以小的部分不能直接排除,排除大的一半
  • 从剩余的区域的右上角或则左下角开始,因为这两个角落的数字很特别,同时是一行的最大,一列的最小或者是一行的最小,一列的最大。这样只要不满足寻找的数字,就能排除一行或则一列。

代码

class Solution {
public:
	bool Find(int target, vector<vector<int> > array) {
		int column_temp = 0, column_max = array[0].size() - 1;
		while (column_max - 1 > column_temp)
		{
			int temp = (column_temp + column_max) / 2;
			if (array[0][temp] > target)
				column_max = temp;
			else if (array[0][temp] < target)
				column_temp = temp; 
			else
				return true;
		}

		int row_temp = 0, row_max = array.size() - 1;
		while (row_max - 1 > row_temp)
		{
			int temp = (row_temp + row_max) / 2;
			if (array[temp][0] > target)
				row_max = temp;
			else if(array[temp][0] < target)
				row_temp = temp;
			else
				return true;
		}

		for (int i = 0; i <= row_max; ++i) {
			for (int j = column_max; j >= 0; ){
				if (array[i][j] > target)
					--j;
				else if (array[i][j] < target)
					break;
				else
					return true;
			}
		}

		return false;
	}
};

结果

11ms,1500k