74. Search a 2D Matrix

来源:互联网 发布:ehshig软件 编辑:程序博客网 时间:2024/06/03 06:47

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,   3,  5,  7],  [10, 11, 16, 20],  [23, 30, 34, 50]]

Given target = 3, return true.


由题意得,是要在m * n的矩阵里面找到给出的target值,而且是矩阵是排好序的,所以我的做法是,先确定target值留在哪一行,然后对行进行二分查找。其实还可以有更好的做法,是直接对行和列进行二分查找,那我打算把两种做法都写出来,第一种的时间复杂度是O(m + logn)

Code(LeetCode运行9ms)

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {        if (matrix.size() == 0 || matrix[0].size() == 0) {            return false;        }        int col = matrix[0].size();        int row = matrix.size();        for (int i = 0; i < row; i++) {            if (target == matrix[i][0] || target == matrix[i][col - 1]) {                return true;            }            if (target > matrix[i][0] && target < matrix[i][col - 1]) {                return GaoMian(matrix[i], target, 0, col - 1);            }        }        return false;    }        bool GaoMian(vector<int> nums, int target, int start, int end) {        if (start > end) {            return false;        }        int mid = start + (end - start) / 2;        if (target == nums[mid]) {            return true;        } else if (target > nums[mid]) {            return GaoMian(nums, target, mid + 1, end);        } else {            return GaoMian(nums, target, start, mid - 1);        }    }};


第二种做法的时间复杂度是O(logn),代码如下:

bool searchMatrix(vector<vector<int>>& matrix, int target) {        if (matrix.empty()) {            return false;        }        int col = matrix[0].size();        int row = matrix.size();        int start = 0, end = col * row;        while (start < end) {            int mid = start + (end - start) / 2;            if (matrix[mid / col][mid % col] == target) {                return true;            } else if (matrix[mid / col][mid % col] > target) {                end = mid;            } else {                start = mid + 1;            }        }        return false;    }