Leetcode 240. Search a 2D Matrix II
  TEZNKK3IfmPf 2023年11月14日 20 0

题目链接:​​Search a 2D Matrix II​​

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.

  此题是74题​​Search a 2D Matrix​​​的升级版,所给出的矩阵性质相对74题少了一条,只保证了每行和每列都是增序的,但依旧有O(m+n)的解法。
  具体思路就是每一行倒着扫,扫到第一个比target小的数就跳到下行,如果等于当然是直接返回true了,如果下一行还比target小就继续跳下一行,直到最后一行。
  为啥这么做是可行的? 可能我比较笨,想了半天才想到。 因为每一列都是增序的,举个例子,假设matrix[0][5] > target,那么[0][5]位置右下(包含右和下)所有元素不可能比target小。

直接上代码

public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length;
if (0 == row)
return false;
int col = matrix[0].length;
int i = 0;
int j = col-1;
while (i < row && j >= 0) {
while (j >= 0 && matrix[i][j] >= target) {
if (matrix[i][j] == target)
return true;
if (j > 0)
j--;
else
break;
}
if (i < row-1)
i++;
else
break;
}
return false;
}
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年04月12日   34   0   0 算法leetcodeC++
  TEZNKK3IfmPf   2024年03月29日   65   0   0 leetcode字符
  TEZNKK3IfmPf   2024年04月19日   50   0   0 leetcode位运算
TEZNKK3IfmPf