19.2.13 [LeetCode 74] 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.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

题意

用矩阵来存储有序序列,高效查找某值

题解

 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int>>& matrix, int target) {
 4         if (matrix.empty()||matrix[0].empty())return false;
 5         int m = matrix.size(), n = matrix[0].size();
 6         for (int i = 0; i < m; i++) {
 7             if (matrix[i][n - 1] < target)continue;
 8             int s = 0, e = n - 1;
 9             while (s <= e) {
10                 int mid = (s + e) / 2;
11                 if (matrix[i][mid] < target)
12                     s = mid + 1;
13                 else
14                     e = mid - 1;
15             }
16             if (matrix[i][s] == target)
17                 return true;
18             else return false;
19         }
20         return false;
21     }
22 };
View Code
posted @ 2019-02-13 20:13  TobicYAL  阅读(121)  评论(0编辑  收藏  举报