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 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM