1. 程式人生 > >19.2.13 [LeetCode 74] Search a 2D Matrix

19.2.13 [LeetCode 74] Search a 2D Matrix

follow etc algo () eve continue sorted mat while

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