Leetcode: Search a 2D Matrix

来源:互联网 发布:mastercamx9编程技巧 编辑:程序博客网 时间:2024/06/05 07:14

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.

二分查找。

class Solution {public:    bool searchMatrix(vector<vector<int> > &matrix, int target) {        int rows = matrix.size();        if (rows == 0) return false;        int cols = matrix[0].size();        if (cols == 0) return false;                bool result = false;        int low_row = 0, up_row = rows - 1;        int low_col = 0, up_col = cols - 1;        int mid_row, mid_col;        while (low_row <= up_row) {            mid_row = (low_row + up_row) / 2;            if (matrix[mid_row][up_col] == target) {                return true;            }            else if (matrix[mid_row][up_col] < target) {                low_row = mid_row + 1;            }            else {                if (matrix[mid_row][low_col] == target) {                    return true;                }                else if (matrix[mid_row][low_col] < target) {                    low_row = up_row = mid_row;                    ++low_col;                    --up_col;                    while (low_col <= up_col) {                        mid_col = (low_col + up_col) / 2;                        if (matrix[mid_row][mid_col] == target) {                            return true;                        }                        else if (matrix[mid_row][mid_col] < target) {                            low_col = mid_col + 1;                        }                        else {                            up_col = mid_col - 1;                        }                    }                                        return false;                }                else {                    up_row = mid_row - 1;                }            }        }                return false;    }};

==================第二次====================

把Matrix看做一个数组来考虑,简单的二分查找。

class Solution {public:    bool searchMatrix(vector<vector<int> > &matrix, int target) {        if (matrix.empty() || matrix[0].empty()) {            return false;        }                int rows = matrix.size();        int cols = matrix[0].size();        int low = 0;        int up = rows * cols - 1;        int mid, midx, midy;        while (low <= up) {            mid = low + (up - low) / 2;            midx = mid / cols;            midy = mid % cols;            if (matrix[midx][midy] == target) {                return true;            }            else if (matrix[midx][midy] < target) {                low = mid + 1;            }            else {                up = mid - 1;            }        }                return false;    }};


0 0
原创粉丝点击