Skip to content

Commit b5d8158

Browse files
committed
二分: 二维数组
Change-Id: I4d53f1048adfae00d1260ba21ce95666c3960abc
1 parent cbf710f commit b5d8158

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/*
2+
* @lc app=leetcode.cn id=74 lang=golang
3+
*
4+
* [74] 搜索二维矩阵
5+
*
6+
* https://leetcode-cn.com/problems/search-a-2d-matrix/description/
7+
*
8+
* algorithms
9+
* Medium (35.89%)
10+
* Likes: 85
11+
* Dislikes: 0
12+
* Total Accepted: 17.3K
13+
* Total Submissions: 48.2K
14+
* Testcase Example: '[[1,3,5,7],[10,11,16,20],[23,30,34,50]]\n3'
15+
*
16+
* 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
17+
*
18+
*
19+
* 每行中的整数从左到右按升序排列。
20+
* 每行的第一个整数大于前一行的最后一个整数。
21+
*
22+
*
23+
* 示例 1:
24+
*
25+
* 输入:
26+
* matrix = [
27+
* ⁠ [1, 3, 5, 7],
28+
* ⁠ [10, 11, 16, 20],
29+
* ⁠ [23, 30, 34, 50]
30+
* ]
31+
* target = 3
32+
* 输出: true
33+
*
34+
*
35+
* 示例 2:
36+
*
37+
* 输入:
38+
* matrix = [
39+
* ⁠ [1, 3, 5, 7],
40+
* ⁠ [10, 11, 16, 20],
41+
* ⁠ [23, 30, 34, 50]
42+
* ]
43+
* target = 13
44+
* 输出: false
45+
*
46+
*/
47+
48+
// @lc code=start
49+
func searchMatrix(matrix [][]int, target int) bool {
50+
if len(matrix) <= 0 || len(matrix[0]) <= 0 {
51+
return false
52+
}
53+
ml, mr := 0, len(matrix)-1 // left/right
54+
for ml < mr { // 0,2 |
55+
mm := ml + (mr-ml)/2 // mid: 1, 1
56+
if matrix[mm][0] == target {
57+
return true
58+
}
59+
if matrix[mm][0] > target {
60+
mr = mm - 1
61+
continue
62+
}
63+
if ml < mm {
64+
ml = mm // 1
65+
continue
66+
}
67+
// 最后两行,ml=mm,判断是否在mr
68+
if matrix[mr][0] == target {
69+
return true // 小剪枝
70+
}
71+
if matrix[mr][0] > target {
72+
mr = mm // 1
73+
continue
74+
}
75+
ml = mm + 1
76+
}
77+
// find in matrix[ml]
78+
row := matrix[ml]
79+
left, right := 0, len(row)-1
80+
for left <= right {
81+
mid := left + (right-left)/2
82+
if row[mid] == target {
83+
return true
84+
}
85+
if row[mid] < target {
86+
left = mid + 1
87+
continue
88+
}
89+
right = mid - 1
90+
}
91+
return false
92+
}
93+
// @lc code=end
94+

0 commit comments

Comments
 (0)