LeetCode74 Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true. (Medium)

分析:

考察题目给的二维数组的特点发现,其本质跟一个排好序的一维数组没有区别,所以就是一个二分查找问题。

对于mid,其对应的点是matrix[mid / n][mid % n]

代码:

 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int>>& matrix, int target) {
 4         int m = matrix.size(), n = matrix[0].size();
 5         int start = 0, end = m * n - 1;
 6         while (start + 1 < end) {
 7             int mid = start + (end - start) / 2;
 8             if (matrix[mid / n][mid % n] == target) {
 9                 return true;
10             }
11             else if (matrix[mid / n][mid % n] < target) {
12                 start = mid;
13             }
14             else {
15                 end = mid;
16             }
17         }
18         if (matrix[start / n][start % n] == target) {
19             return true;
20         }
21         if (matrix[end / n][end % n] == target) {
22             return true;
23         }
24         return false;
25     }
26 };
原文地址:https://www.cnblogs.com/wangxiaobao/p/5910744.html