Search a 2D Matrix

系统管理员 2022-06-03 04:27 274阅读 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.

For example,

Consider the following matrix:

  1. [
  2. [1, 3, 5, 7],
  3. [10, 11, 16, 20],
  4. [23, 30, 34, 50]
  5. ]

Given target = 3, return true.

分析

1. 题目要求

给出一个m * n矩阵,该矩阵每一行都是从小到大排列,每一列也是如此。找出该矩阵中是否含有给出的目标数。

2. 求解思路

  1. 最简单的方法,可以从左到右,从上到下依次遍历整个矩阵看是否含有目标数,但时间复杂度为 O(mn)。

  2. 由于已经排好序了,我们可以依次将每一行的第一个元素和目标数作比较,找出目标数可能在的行数。

    再将该行的每一个元素和目标数作比较,看是否含有目标数。时间复杂度为 O(m + n)。

  3. 其实这个与一维已排序数组查找目标数差不多,可以使用二分查找的方法来求解。

    先使用二分查找(每次与中间的那一行作比较),找到目标数可能在的那一行。

    再继续对目标行使用二分查找,看是否含有目标数。 时间复杂度为 O( log(mn) )。

3. 代码如下

  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();
  6. int n = matrix[0].size();
  7. int a = 0;
  8. int b = m - 1;
  9. int index = (b + a) / 2;
  10. while (b >= a) {
  11. if (matrix[index][0] <= target && matrix[index][n-1] >= target) {
  12. for (int i = 0; i < n; i++) {
  13. if (matrix[index][i] == target) return true;
  14. }
  15. int c = 0, d = n - 1;
  16. int mid = (c + d) / 2;
  17. while (d >= c) {
  18. if (matrix[index][mid] == target) {
  19. return true;
  20. } else if (matrix[index][mid] < target) {
  21. c = mid + 1;
  22. mid = (c + d) / 2;
  23. } else {
  24. d = mid - 1;
  25. mid = (c + d) / 2;
  26. }
  27. }
  28. return false;
  29. } else if (matrix[index][0] > target) {
  30. b = index - 1;
  31. index = (b + a) / 2;
  32. } else if (matrix[index][n-1] < target) {
  33. a = index + 1;
  34. index = (b + a) / 2;
  35. }
  36. }
  37. return false;
  38. }
  39. };

发表评论

表情:
评论列表 (有 0 条评论,274人围观)

还没有评论,来说两句吧...

相关阅读