19.2.13 [LeetCode 74] Search a 2D Matrix
Posted TobicYAL
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 };
以上是关于19.2.13 [LeetCode 74] Search a 2D Matrix的主要内容,如果未能解决你的问题,请参考以下文章
[JavaScript 刷题] 二分搜索 - 搜索二维矩阵, leetcode 74