SearchA2dMatrix

搜索二维矩阵

题目介绍

搜索二维矩阵

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

  • 每行中的整数从左到右按升序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

示例1:

img

1
2
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true

示例2:

img

1
2
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false

提示:

  • m == matrix.length
  • n == matrix[0].length
  • 1 <= m, n <= 100
  • −104<=matrix[i][j],target<=104

题目解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package algorithm;

public class SearchA2dMatrix {

public static boolean searchMatrix(int[][] matrix, int target) {

int row = matrix.length;
int col = matrix[0].length;

int rowLow = 0;
int rowHigh = row - 1;
int midRow = 0;
while (rowLow <= rowHigh) {
midRow = (rowLow + rowHigh) / 2;
if (matrix[midRow][0] == target) {
return true;
} else if (matrix[midRow][0] > target) {
rowHigh = midRow - 1;
} else {
rowLow = midRow + 1;
}
}
if (matrix[midRow][0] > target) {
midRow -= 1;
}

if (midRow < 0) {
return false;
}

int colLeft = 0;
int colRight = col - 1;
int midCol;
while (colLeft <= colRight) {
midCol = (colLeft + colRight) / 2;
if (matrix[midRow][midCol] == target) {
return true;
} else if (matrix[midRow][midCol] > target) {
colRight = midCol - 1;
} else {
colLeft = midCol + 1;
}
}

return false;
}

public static void main(String[] args) {

int[][] matrix = new int[][]{{1,3,5,7}, {10,11,16,20}, {23,30,34,60}};
int target = 3;
System.out.println(searchMatrix(matrix, target));

matrix = new int[][]{{1,3,5,7}, {10,11,16,20}, {23,30,34,60}};
target = 13;
System.out.println(searchMatrix(matrix, target));
}
}

打印:

1
2
true
false

思路:

思路很简单,就是二分搜索。


SearchA2dMatrix
https://yangtzeshore.github.io/2021/05/11/SearchA2dMatrix/
作者
Chen Peng
发布于
2021年5月11日
许可协议