0%

Leetcode240 Search a 2D Matrix II

Leetcode240 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.

Example:

Consider the following matrix:

1
2
3
4
5
6
7
[
[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.

思路

两个指针,一个控制row,一个控制column,因为整个Matrix是有序的,则如果该数比最后一个column(即每一行最大的数)小,则column指针向左移动,如果该数比第一个row大(即每一行最小的数)则row指针向下移动。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if( matrix.length==0||matrix[0].length==0) return false;
int m = matrix.length;

int r=0;
int c=matrix[0].length-1;

while(r<m&&c>=0){
if(target==matrix[r][c])
return true;
else if(target<matrix[r][c])
c--;
else
r++;
}
return false;
}
}
-------------本文结束感谢您的阅读-------------

Welcome to my other publishing channels