码迷,mamicode.com
首页 > 其他好文 > 详细

【Search a 2D Matrix】cpp

时间:2015-05-19 18:08:14      阅读:171      评论:0      收藏: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,   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) {
            if (matrix.size()==0) return false;
            const int ROW = matrix.size();
            const int COL = matrix[0].size();
            // search the target row
            int begin = 0;
            int end = ROW-1;
            while ( begin<=end )
            {
                int mid = (begin+end)/2;
                int lower = matrix[mid][0];
                int upper = matrix[mid][COL-1];
                if ( target>=lower && target<=upper )
                {
                    return Solution::binarySearch(matrix[mid], target);
                }
                if ( target<lower )
                {
                    end = mid-1;
                    continue;
                }
                if ( target>upper )
                {
                    begin = mid+1;
                    continue;
                }
            }
            return false;
    }
    static bool binarySearch(vector<int>& row, int target)
    {
            int begin = 0;
            int end = row.size()-1;
            while ( begin<=end )
            {
                int mid = (begin+end)/2;
                if ( row[mid]==target ) return true;
                if ( row[mid]>target )
                {
                    end = mid-1;
                }
                else
                {
                    begin = mid+1;
                }
            }
            return false;
    }
};

tips:

1. 首先二分查找可能所在的行

2. 确定某一行之后,再二分查找所在的列

完毕。

【Search a 2D Matrix】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4514943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!