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

【LeetCode从零单刷】Search a 2D Matrix

时间:2015-10-30 12:41:27      阅读:205      评论: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.

解答:

因为排序过,思路很清晰。建立每行首元素的索引,然后行二分搜索,最后列二分搜索。复杂度是O(lg(m) + lg(n))。但是难点在于细节:

  1. 这里的搜索可能 False,也就是找不到元素。因此,如果 first = 1,last = 2,mid = (first + last)/2 = 1。下一次如果 first = mid = 1,又陷入了循环;
  2. 因为除法取整的原因,有可能 last 一直无法取到。如果 first = 1,last = 2,mid = (first + last)/2 = 1。下一次如果 first = mid = 1,还是取不到 last = 2 的值。因此需要多判断一次 last 的值;
  3. 关于每行首元素的索引中的搜索,不同于列搜索。即使 target > 索引中的最大值,还是有可能存在此元素。例如 target = 30 > 23,依然存在
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        vector<int> rowfirst;
        for(int i=0; i<matrix.size(); i++)  rowfirst.push_back(matrix[i][0]);
        
        int head = 0;
        int tail = matrix.size() - 1;
        while(head <= tail){
            if(head + 1 == tail || head == tail){
                if(target == rowfirst[head] || target == rowfirst[tail])   return true;
                else    break;
            }
            int mid = (head + tail) / 2;
            if(target > rowfirst[tail])  head = tail;
            else if(target == rowfirst[mid] || target == rowfirst[tail])  return true;
            else if(target < rowfirst[mid])   tail = mid;
            else if(target > rowfirst[mid])   head = mid;
        }
        if(head > tail) return false;
        
        int first = 0;
        int last  = matrix[0].size() - 1;
        while(first <= last){
            if(first == last || first + 1 == last){
                if (matrix[head][first] == target || matrix[head][last] == target)   return true;
                else    return false;
            }
            int mid = (first + last) / 2;
            if(target == matrix[head][mid] || target == matrix[head][last])   return true;
            else if(target < matrix[head][mid])   last = mid;
            else if(target > matrix[head][mid])   first = mid;
        }
        return false;
    }
};

版权声明:本文为博主原创文章,转载请联系我的新浪微博 @iamironyoung

【LeetCode从零单刷】Search a 2D Matrix

标签:

原文地址:http://blog.csdn.net/ironyoung/article/details/49507773

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