File tree 2 files changed +83
-0
lines changed
solution/074.Search a 2D Matrix
2 files changed +83
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 搜索二维矩阵
2
+
3
+ ### 问题描述
4
+ 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
5
+
6
+ - 每行中的整数从左到右按升序排列。
7
+ - 每行的第一个整数大于前一行的最后一个整数。
8
+
9
+ ```
10
+ 示例 1:
11
+ 输入:
12
+ matrix = [
13
+ [1, 3, 5, 7],
14
+ [10, 11, 16, 20],
15
+ [23, 30, 34, 50]
16
+ ]
17
+ target = 3
18
+ 输出: true
19
+
20
+ 示例 2:
21
+ 输入:
22
+ matrix = [
23
+ [1, 3, 5, 7],
24
+ [10, 11, 16, 20],
25
+ [23, 30, 34, 50]
26
+ ]
27
+ target = 13
28
+ 输出: false
29
+ ```
30
+
31
+ ### 思路
32
+
33
+ 1 . 因为矩阵按特性排列,所以先定位行坐标
34
+ 2 . 定位行坐标后直接调函数
35
+
36
+ 一开始本来想定位到行之后用二分查找的,但是考虑到这个元素本身可能不存在,所以建议不调迭代器的话用顺序查找吧
37
+
38
+ ``` CPP
39
+ class Solution {
40
+ public:
41
+ bool searchMatrix(vector<vector<int >>& matrix, int target) {
42
+ if(matrix.empty())return false;
43
+
44
+ size_t row = matrix.size();
45
+ size_t column = matrix[ 0] .size();
46
+ if(column == 0 || column == 0)return false;
47
+
48
+ if(target < matrix[ 0] [ 0 ] || target > matrix[ row-1] [ column-1 ] )return false;
49
+
50
+ for(int i = 0;i<row;i++){
51
+ if(matrix[ i] [ column-1 ] <target)continue;
52
+
53
+ auto iter = find(matrix[i].begin(),matrix[i].end(),target);
54
+ if(iter != matrix[i].end())return true;
55
+ else return false;
56
+ }
57
+
58
+ return false ;
59
+ }
60
+ };
61
+ ```
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ bool searchMatrix (vector<vector<int >>& matrix, int target) {
4
+ if (matrix.empty ())return false ;
5
+
6
+ size_t row = matrix.size ();
7
+ size_t column = matrix[0 ].size ();
8
+ if (column == 0 || column == 0 )return false ;
9
+
10
+ if (target < matrix[0 ][0 ] || target > matrix[row-1 ][column-1 ])return false ;
11
+
12
+ for (int i = 0 ;i<row;i++){
13
+ if (matrix[i][column-1 ]<target)continue ;
14
+
15
+ auto iter = find (matrix[i].begin (),matrix[i].end (),target);
16
+ if (iter != matrix[i].end ())return true ;
17
+ else return false ;
18
+ }
19
+
20
+ return false ;
21
+ }
22
+ };
You can’t perform that action at this time.
0 commit comments