LeetCode Search a 2D Matrix II

题目:

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

For example,

Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

题意:

给定一个二维数组,并且在这个二维数组中,每一行的元素都是递增的,并且每一列的元素也是递增的,与之前的那一题有区别了,之前的那一题是保证每一行的开头的那个元素的值都要比上一行的每个元素大,而此题怎没有这个限定。所以在解决这道题目的时候,就要考虑一些新的方法,而此题在《剑指offer》中也有,思路非常好。

题解:

首先我们找到第一行的最右边的那个元素,因为基于这个二维数组的特征,所以我们可以看到如果要找的这个数比第一行的有右边的那个数要大,那么,说明接下来我只需要在从二行开始的这个矩阵中找就行了;否则,如果要找的这个数比最右边的数要小,那么我就可以直接在比现在这一列小一列的那个矩阵中找就行了。以此类推。思路还是非常好理解的,不懂可以看看《剑指offer》一书,在P38,二维数组中的查找。

<span style="font-size:14px;">public class Solution 
{
    public boolean searchMatrix(int[][] matrix,int target)
	{
		int rowlength = matrix.length;
		int collength = matrix[0].length;
	    return isFind(matrix,rowlength,collength,target);
	}
	public boolean isFind(int[][] matrix,int rows,int cols,int target)
	{
		boolean find = false;
		if(matrix != null && rows > 0 && cols > 0)
		{
			int row = 0;        //第一行
			int column = cols - 1;  //从最右边那一列开始
			while(row < rows && column >= 0)
			{
				if(matrix[row][column] == target)
				{
					find = true;
					break;
				}
				else if(matrix[row][column] > target)
				{
					column--;
				}
				else if(matrix[row][column] < target)
					row++;
			}
		}
		return find;
	}
}</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值