96_leetcode_Search a 2D Matrix

来源:互联网 发布:淘宝双十一活动要求 编辑:程序博客网 时间:2024/04/29 18:21

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.

1:特殊情况;2:采用二分查找的方法来判断二纬数字的数字是不是所需要查找的数字;3:注意中间的值如何转化为二维矩阵的数字

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



0 0
原创粉丝点击