力扣 题目74- 搜索二维矩阵

题目

题解

先对第一列进行二分搜索 找到对应行

再对 对应行进行二分搜索

代码

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 class Solution {
 5 public:
 6     bool searchMatrix(vector<vector<int>>& matrix, int target) {
 7         //1.二分搜索找行 如果存在直接返回
 8         int xnumber = matrix.size()-1;
 9         int ynumber = matrix[0].size()-1;
10         int line = xnumber / 2;
11         int left = 0;
12         int right = xnumber;
13         while (true)
14         {
15             line = (left + right) / 2 ;
16             if (matrix[line][0] == target) {
17                 return 1;
18             }
19             if (left == right || right < left) {
20                 //在二分搜索中 最后的结果有可能是 matrix[left][0] > target;
21                 //我们要找到是比target小的 所以left=left - 1
22                 if (matrix[left][0] > target) {
23                     left=left - 1;
24                 }
25                 //left < 0 说明target<matrix[0][0] 肯定没有这个数
26                 if (left < 0) {
27                     return 0;
28                 }
29                 line = left;
30                 break;
31             }
32             else if(matrix[line][0] < target)
33             {
34                 left = line + 1;
35             }
36             else if (matrix[line][0] > target)
37             {
38                 right= line - 1;
39             }
40         }
41         //2.找到行再进行二分搜索
42         left = 0;
43         right = ynumber;
44         int center = (right + left) / 2;
45         while (true)
46         {
47             center = (left + right) / 2;
48             if (matrix[line][center] == target) {
49                 return 1;
50             }
51             if (left == right|| right< left) {
52                 return 0;
53             }
54             else if (matrix[line][center] < target)
55             {
56                 left = center + 1;
57             }
58             else if (matrix[line][center] > target)
59             {
60                 right = center - 1;
61             }
62         }
63         return 0;
64     }
65 };
66 
67 int main() {
68     Solution sol;
69 
70     vector<vector<int>> matrix = { {1} };
71     bool result=sol.searchMatrix(matrix,0);
72     cout << result << endl;
73 }
View Code

 

posted @ 2022-06-26 16:24  无聊的阿库娅  阅读(23)  评论(0编辑  收藏  举报