LeetCode 74: Search A 2D Matrix

来源:互联网 发布:tensorflow gpu 显卡 编辑:程序博客网 时间:2024/04/28 22:02

Difficulty: 3

Frequency: 3


Problem:

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.


Solution:

1. The first simple solution is treat the whole matrix as a long array. And use binary search. Time complexity is O(log(M*N)). M is the number of rows and N is the number of columns.

class Solution {public:    bool searchMatrix(vector<vector<int> > &matrix, int target) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        return searchMatrixRecursive(matrix, target, 0, matrix.size()*matrix[0].size() - 1);    }    bool searchMatrixRecursive(vector<vector<int> > &matrix, int target, int i_start, int i_end)    {        int i_middle = (i_start+i_end)/2;        int i_row, i_col;        GetRowAndCol(i_middle, matrix[0].size(), i_row, i_col);        if (matrix[i_row][i_col]==target)            return true;        else if (i_start==i_end)            return false;                    if (target<matrix[i_row][i_col])            return searchMatrixRecursive(matrix, target, i_start, (i_middle-1)>i_start?(i_middle-1):i_start);        else            return searchMatrixRecursive(matrix, target, i_middle + 1, i_end);    }    void GetRowAndCol(int i_value, int i_row_length, int & i_row, int & i_col)    {        i_col = i_value%i_row_length;        i_row = i_value/i_row_length;    }};

2. The next method is first use binary search in the first column and find the row that target may be in. And then use binary search again in the row that we find. The time complexity is O(logM) + O(logN) = O(log(M*N)) which is the same as the first one.


Notes:

Variant of binary search.