leetcode-面试题04.二维数组中的查找

1. 暴力法遍历

  双重循环遍历二维数组,直到matrix[i][j]==target,返回true。未利用到题目中所说的行递增、列递增的特点。

  • 二维数组的行列长度判断:行长度matrix.length;列长度matrix[0].length
  • 二维数组为空的判断
    matrix[0].length=0和matrix.length=0都代表矩阵为空,只有一行或一列的情况必有一length=1,而非0 .
    f a l s e = { m a t r i x . n u l l 首地址为空 m a t r i x . l e n g t h = = 0 二维数组是否为{ }  m a t r i x . l e n g t h = = 1 & & m a t r i x [ 0 ] . l e n g t h = = 0 二维数组是否为{{}} false= \begin{cases} matrix.null& \text{首地址为空}\\ matrix.length==0& \text{二维数组是否为\{ \} }\\ matrix.length==1 \&\& matrix[0].length==0 & \text{二维数组是否为\{\{\}\}} \end{cases} false=matrix.nullmatrix.length==0matrix.length==1&&matrix[0].length==0首地址为空二维数组是否为{ } 二维数组是否为{{}}
    即:if(matrix==null || matrix.length==0 || matrix[0].length==0) { return false;}
  • 时间复杂度O(n*m);空间复杂度O(1)
public boolean findNumberIn2DArray(int[][] matrix, int target) {		
		if(matrix==null || matrix.length==0 || matrix[0].length==0) {
			return false;
		}
		int rowlength = matrix.length;
		int colength = matrix[0].length;
		for(int i=0;i<rowlength;i++) {
			for(int j=0;j<colength;j++) {
				if(matrix[i][j]==target)
					return true;
			}
		}
		return false;
	}
2. 逐行二分查找

  利用了行递增的特点:每行数据均有序,首先想到的就是利用二分查找的方法查找元素。

public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if(matrix==null || matrix.length==0 || matrix[0].length==0) {
			return false;
		}
		int rowlength = matrix.length;
		for(int i=0;i<rowlength;i++) {
			if(Arrays.binarySearch(matrix[i], target) >= 0)
				return true;
		}
		return false;
	}
3. 矩阵消除法(自命名)

  利用行递增、列递增的特点:矩阵的右上角元素是该行的最大值、该列的最小值,那么:
(1)若target>当前元素,target在该元素所在行的下方,即可消去该元素的所在行
(2)若target<当前元素,target在该元素所在列的左方,即可消去该元素的所在列

  • 最多查找次数是从右上角查找,而target恰好在左下角才找到或找不到的情况(走了直角),即m+n次查找。
  • 时间复杂度O(n+m),空间复杂度O(1)
public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if(matrix==null || matrix.length==0 || matrix[0].length==0) {
			return false;
		}
		int rowlength = matrix.length;
		int colength = matrix[0].length;
		int i=rowlength-1, j=0;
		while(i>=0 && j<colength) {
			if(target>matrix[i][j])
				j++;
			else if(target<matrix[i][j])
				i--;
			else return true;
		}
		return false;			
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值