Search a 2D Matrix II

本文介绍了一种在二维矩阵中搜索特定值的算法,该矩阵的特点是每一行和每一列都是升序排列。通过从矩阵的右上角开始,根据目标值与当前值的大小关系逐步缩小搜索范围,实现了O(m+n)的时间复杂度。

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

The reference link: http://www.code123.cc/docs/leetcode-notes/binary_search/search_a_2d_matrix_ii.html

题解 - 自右上而左下

  1. 复杂度要求——O(m+n) time and O(1) extra space,同时输入只满足自顶向下和自左向右的升序,行与行之间不再有递增关系,与上题有较大区别。时间复杂度为线性要求,因此可从元素排列特点出发,从一端走向另一端无论如何都需要m+n步,因此可分析对角线元素。
  2. 首先分析如果从左上角开始搜索,由于元素升序为自左向右和自上而下,因此如果target大于当前搜索元素时还有两个方向需要搜索,不太合适。
  3. 如果从右上角开始搜索,由于左边的元素一定不大于当前元素,而下面的元素一定不小于当前元素,因此每次比较时均可排除一列或者一行元素(大于当前元素则排除当前行,小于当前元素则排除当前列,由矩阵特点可知),可达到题目要求的复杂度。
  4. public class Solution {
        /**
         * @param matrix: A list of lists of integers
         * @param: A number you want to search in the matrix
         * @return: An integer indicate the occurrence of target in the given matrix
         */
        public int searchMatrix(int[][] matrix, int target) {
            // write your code here
            int count = 0;
            if (matrix == null || matrix.length == 0) {
                return count;
            }
            if (matrix[0] == null || matrix[0].length == 0) {
                return count;
            }
            
            int nRow = matrix.length;
            int nCol = matrix[0].length;
            
            if (matrix[0][0] > target || matrix[nRow - 1][nCol - 1] < target) {
                return count;
            }
            
            int i = 0;
            int j = nCol - 1;
            while (i < nRow && j >= 0) {
                if (matrix[i][j] > target) {
                    j--;
                } else if (matrix[i][j] < target) {
                    i++;
                } else {
                    i++;
                    j--;
                    count++;
                }
            }
            
            return count;
            
        }
    }

     

转载于:https://www.cnblogs.com/codingEskimo/p/6834058.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值