38 - 搜索二维矩阵 II

本文介绍了一种在有序二维矩阵中搜索特定目标值的方法。通过不断缩小搜索范围来提高搜索效率,适用于行和列都按升序排列的矩阵。

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

2017.9.19

就是不断缩小检索范围就可以了

public class Solution {
    /*
     * @param matrix: A list of lists of integers
     * @param target: An integer you want to search in matrix
     * @return: An integer indicate the total occurrence of target in the given matrix
     */
	public static int searchMatrix(int[][] matrix, int target) {
	        // write your code here
		int count = 0;
		if(matrix == null){
			return count;
		}
		int n = matrix.length-1;
		if( n < 0 || matrix[0] == null){
			return count;
		}
		int m = matrix[0].length-1;
		if( m < 0){
			return count;
		}
		/**
		 * 1看  matrix[0][i],如果matrix[0][i] >= target 那么right = i-1;
		 * 2看  matrix[n-1][j] 如果matrix[n-1][j] <= targer 那么 left = j+1;
		 * 3看 matrix[right][k],如果 matrix[right][k] <= target 那么 up = k + 1;
		 * 4看 matrix[left][h],如果 matrix[left][h] >= targer 那么down = h-1;
		 *  ****/
		int left = 0;
		int up = 0;
		int right = m;
		int down = n;
		for(int i = 0; i <= m; i++){
			if(matrix[down][i] < target){
				left = i+1;
			}
			if(matrix[up][i] <= target){
				right = i;
			}
		}
		for(int i = 0; i <= n; i++){
			if(matrix[i][right] < target){
				up = i+1;
			}
			if(left <= m && matrix[i][left] <= target){
				down = i;
			}
		}
		for(int i = left; i <= right;i++){
			for(int j = up; j <= down;j++){
				if(matrix[j][i] == target){
					count++;
				}
			}
		}
		return count;	
	}
}


### 关于二维矩阵的操作及相关信息 #### 什么是二维矩阵二维矩阵是一种常见的数据结构,通常表示为一个由行和列组成的矩形数组。它广泛应用于科学计算、机器学习以及图形处理等领域。 #### 增强对称矩阵的灵活性 为了提高对称矩阵的数据和结构适应性,可以通过引入稀疏矩阵或动态矩阵等技术实现[^1]。这些方法特别适用于处理不规则和复杂的矩阵数据。 #### 稀疏矩阵及其应用场景 如果在一个矩阵中零元素的数量远大于非零元素数量,并且非零元素分布无明显规律,则该矩阵被称为稀疏矩阵[^2]。稀疏矩阵的主要应用领域包括但不限于网络分析、大规模线性方程求解以及自然语言处理中的词频统计等问题。 #### 搜索二维矩阵的方法 对于给定的一个 m×n 的二维矩阵,在某些情况下可以将其视为一维有序数组来进行高效查询操作。例如采用二分查找法能够达到 O(log(m*n)) 时间复杂度的效果[^3]。下面是一个 Python 实现的例子: ```python def searchMatrix(matrix, target): if not matrix or not matrix[0]: return False rows, cols = len(matrix), len(matrix[0]) low, high = 0, rows * cols - 1 while low <= high: mid = (low + high) // 2 num = matrix[mid // cols][mid % cols] if num == target: return True elif num < target: low = mid + 1 else: high = mid - 1 return False ``` 此函数实现了基于上述理论的搜索逻辑。 #### 螺旋矩阵与旋转图像 除了基本的搜索功能外,还有其他涉及二维矩阵的经典问题如螺旋遍历矩阵或者顺/逆时针方向旋转图片90°角等。这些问题一般具有较高时间复杂度 O(N*N)[^4] ,但得益于巧妙设计的空间优化策略仍能保持较低资源消耗。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值