首页 > 其他 > 详细

19.2.13 [LeetCode 74] Search a 2D Matrix

时间:2019-02-13 21:03:40      阅读:154      评论:0      收藏:0      [点我收藏+]

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

19.2.13 [LeetCode 74] Search a 2D Matrix

原文:https://www.cnblogs.com/yalphait/p/10371693.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!