Skip to content

Commit 6540d8d

Browse files
committed
240.搜索二维矩阵II,二分查找
1 parent 60b639f commit 6540d8d

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
234. 回文链表
8787
236. 二叉树的最近公共祖先
8888
239. 滑动窗口最大值
89+
240. 搜索二维矩阵 II
8990
279. 完全平方数
9091
283. 移动零
9192
287. 寻找重复数

leetcode_Java/DoneType.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@
152152
169. 多数元素(排序,哈希表,投票,计数,分治)
153153
215. 数组中的第K个最大元素(快速排序,堆排序)
154154
239. 滑动窗口最大值(单调递减双端队列)
155+
240. 搜索二维矩阵 II(二分查找)
155156
283. 移动零(双指针)
156157
287. 寻找重复数(哈希表,快慢指针,二分查找,位运算)
157158
303. 区域和检索 - 数组不可变(前缀和)

leetcode_Java/Solution0240.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// 240. 搜索二维矩阵 II
2+
3+
4+
/*
5+
二分查找:
6+
1、从左下角开始,在有效边界范围内,元素小于目标值则右移,元素大于目标值则上移
7+
2、如果找到了目标值则返回true,遍历结束后没找到目标值则返回false
8+
*/
9+
class Solution {
10+
public boolean searchMatrix(int[][] matrix, int target) {
11+
int m = matrix.length, n = matrix[0].length;
12+
int row = m - 1, col = 0;
13+
while (row >= 0 && col < n) {
14+
if (matrix[row][col] == target) {
15+
return true;
16+
} else if (matrix[row][col] < target) {
17+
col++;
18+
} else {
19+
row--;
20+
}
21+
}
22+
return false;
23+
}
24+
}

0 commit comments

Comments
 (0)