Skip to content

Commit aa2c708

Browse files
committed
74
1 parent 6c96d0b commit aa2c708

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

SUMMARY.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,5 @@
7373
* [70. Climbing Stairs](leetCode-70-Climbing-Stairs.md)
7474
* [71. Simplify Path](leetCode-71-Simplify-Path.md)
7575
* [72. Edit Distance](leetCode-72-Edit-Distance.md)
76-
* [73. Set Matrix Zeroes](leetcode-73-Set-Matrix-Zeroes.md)
76+
* [73. Set Matrix Zeroes](leetcode-73-Set-Matrix-Zeroes.md)
77+
* [74. Search a 2D Matrix](leetCode-74-Search-a-2D-Matrix.md)

leetCode-74-Search-a-2D-Matrix.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# 题目描述(中等难度)
2+
3+
![](https://windliang.oss-cn-beijing.aliyuncs.com/74.jpg)
4+
5+
判断一个矩阵中是否存在某个数,矩阵是有序的。
6+
7+
# 解法一 二分法
8+
9+
看到了有序序列,啥都不用想直接二分,只需要考虑到怎么把二分时候的下标转换为矩阵的行、列下标就可以了,很简单,用除法和求余就够了。
10+
11+
```java
12+
public boolean searchMatrix(int[][] matrix, int target) {
13+
int rows = matrix.length;
14+
if (rows == 0) {
15+
return false;
16+
}
17+
int cols = matrix[0].length;
18+
int left = 0;
19+
int right = rows * cols - 1;
20+
while (left <= right) {
21+
int mid = (left + right) / 2;
22+
int temp = matrix[mid / cols][mid % cols];
23+
if (temp == target) {
24+
return true;
25+
} else if (temp < target) {
26+
left = mid + 1;
27+
} else {
28+
right = mid - 1;
29+
}
30+
}
31+
return false;
32+
}
33+
```
34+
35+
时间复杂度:O ( log ( n ) )。
36+
37+
空间复杂度:O ( 1 )。
38+
39+
#
40+
41+
这道题的二分法,比较简单,大家可以看下[33题](<https://leetcode.windliang.cc/leetCode-33-Search-in-Rotated-Sorted-Array.html>),相信对二分法会有一个更深刻的理解。

0 commit comments

Comments
 (0)