[LeetCode] Search a 2D Matrix II

本文介绍了一种高效的矩阵搜索算法,从矩阵右上角开始,通过比较目标值与当前元素缩小搜索范围,逐步逼近目标值所在位置。

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

Well, the idea is to search from the top-right element and then reduce the range for further searching by comparisons between target and the current element.

Let's take the matrix in the problem statement as an example.

[
  [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]
] 

Suppose we want to search for 12. We first initialize r = 0 and c = 4. We compare 12 withmatrix[r][c] = matrix[0][4] = 15 and 12 < 15, so 12 cannot appear in the column of 15 since all elements below 15 are not less than 15. Thus, we decrease c by 1 and reduce the search range by a column. Now we compare 12 with matrix[r][c] = matrix[0][3] = 11 and 12 > 11, so 12 cannot appear in the row of 11 since all elements left to 11 are not greater than 11. Thus, we increase r by 1 and reduce the search range by a row. Then we reach matrix[1][3] = 12 = target and we are done (return true). If we have moved beyond the matrix and have not found the target, return false.

Putting these together, we will have the following short codes.


C++

 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int>>& matrix, int target) {
 4         int m = matrix.size(), n = matrix[0].size(), r = 0, c = n - 1;
 5         while (r < m && c >= 0) {
 6             if (matrix[r][c] == target) return true;
 7             if (matrix[r][c] > target) c--;
 8             else r++;
 9         }
10         return false;
11     } 
12 };

Python

 1 class Solution:
 2     # @param {integer[][]} matrix
 3     # @param {integer} target
 4     # @return {boolean}
 5     def searchMatrix(self, matrix, target):
 6         m, n, r, c = len(matrix), len(matrix[0]), 0, n - 1
 7         while r < m and c >= 0:
 8             if matrix[r][c] == target:
 9                 return True
10             if matrix[r][c] > target:
11                 c -= 1
12             else: 
13                 r += 1
14         return False

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4675650.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值