LeetCode 74. 搜索二维矩阵(Search a 2D Matrix)

题目描述

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

  • 每行中的整数从左到右按升序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

示例 1:

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

示例 2:

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

解题思路

用二分查找的思想,首先对找到目标存在的行,即对每行第一个数字组成的序列进行二分查找,定位到第一个数小于或等于目标的行;接着在当前行继续二分查找,直到找到目标数返回true或者未找到返回false

代码

 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int>>& matrix, int target) {
 4         if(matrix.empty()) return false;
 5         int rows = matrix.size(), cols = matrix[0].size();
 6         double up = 0, btm = rows - 1; //注意此处必须设为double型,因为计算中间行时要向上取整
 7         while(up < btm){
 8             int row = ceil((up + btm) / 2);
 9             if(matrix[row][0] == target) return true;
10             else if(matrix[row][0] > target) btm = row - 1;
11             else up = row;
12         }
13         int left = 0, right = cols - 1;
14         while(left <= right){
15             int col = (left + right) / 2;
16             if(matrix[up][col] == target) return true;
17             else if(matrix[up][col] < target) left = col + 1;
18             else right = col - 1;
19         }
20         return false;
21     }
22 };
原文地址:https://www.cnblogs.com/wmx24/p/9371096.html