LeetCode 240. Search a 2D Matrix II Java

本文介绍了一种高效的矩阵搜索算法,用于在一个具有特定排序属性的二维矩阵中查找特定值。该算法首先确定目标值可能存在的行和列,然后在这行和列上进行二分查找,大大提高了搜索效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

 

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.

 

题意:给出一个m*n的二维矩阵,具有以下特点:

    (1)每一行按照升序排序

  (2)每一列按照升序排列

现给出一个值,求该值是否在二维矩阵中存在。这里直接二次循环查找时间复杂度为o(m*n),肯定会超时的。所以我先查找可能出现target的列和行,然后对可能的行和列分别做二分查找。

 

代码:

public class Solution {

	public boolean searchMatrix(int[][] matrix, int target) {
	
		if(matrix.length==0||matrix[0].length==0)		//空矩阵返回false
			return false;
		int row=matrix.length;
		int col=matrix[0].length;
		
		
		int mayRow=-1;		//可能的行
		int mayCol=-1;		//可能的列
		for(int i=0;i<row;i++){		//寻找可能出现target的行
			if(matrix[i][0]<=target&&matrix[i][col-1]>=target){
				mayRow=i;
				int low=0;
				int high=col-1;
				while(low<=high){
					int mid=(low+high)/2;
					if(matrix[mayRow][mid]==target){
						System.out.println("true");
						return true;
					}else if(matrix[mayRow][mid]>target){
						high=mid-1;
					}else if(matrix[mayRow][mid]<target){
						low=mid+1;
					}
				}
			}
		}
		
		for(int i=0;i<col;i++){	//寻找可能出现target的列
			if(matrix[0][i]<=target&&matrix[row-1][i]>=target){
				mayCol=i;
				int low=0;
				int high=row-1;
				while(low<=high){
					int mid=(low+high)/2;
					if(matrix[mid][mayCol]==target){
						System.out.println("true");
						return true;
					}else if(matrix[mid][mayCol]>target){
						high=mid-1;
					}else if(matrix[mid][mayCol]<target){
						low=mid+1;
					}
				}
			}
		}
		System.out.println("false");
		return false;
	}
}

  

  

 

 

转载于:https://www.cnblogs.com/271934Liao/p/6909124.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值