Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

A trickier binary search one.

//////////////
class Solution 
{    
    int lower_bound_vert(vector<vector<int>>& m, int col, int i, int j, int target)
    {
        int ret = j + 1;
        if (m[j][col] < target) return ret;
        else ret = j;
        int l = i, r = j;
        while (l < r)
        {
            int mid = l + ((r - l) >> 1);
            if (m[mid][col] == target)
                return mid;
            else if (m[mid][col] < target)
                l = mid + 1;
            else if (m[mid][col] > target)
            {                
                r = mid;
                ret = mid;
            }
        }
        return ret;
    }
public:
    bool searchMatrix(vector<vector<int>>& m, int target) 
    {
        size_t rows = m.size();
        if (rows == 0) return false;
        size_t cols = m[0].size();

        //    Prune vertically
        auto it0 = std::lower_bound(m[0].begin(), m[0].end(), target);
        if (it0 != m[0].end() && *it0 == target) return true;
        int max_c = 0;
        if (it0 == m[0].begin())    return false;
        else                        max_c = it0 - m[0].begin();

        //    Prune horizontally                
        int max_r = lower_bound_vert(m, 0/*col_0*/, 0, rows - 1, target);
        if (max_r == 0)    return false;
        if (max_r < rows && m[max_r][0] == target)  return true;

        //    Pick cols
        int start_row = lower_bound_vert(m, max_c - 1, 0, max_r - 1, target);        
        if (start_row == max_r) return false;
        if (m[start_row][max_c - 1] == target) return true;
        while (start_row < max_r)
        {
            if (std::binary_search(m[start_row].begin(), m[start_row].begin() + max_c, target))
                return true;
            start_row++;
        }

        return false;
    }
};

But there are always smarter\shorter solution: https://leetcode.com/discuss/47528/c-with-o-m-n-complexity

posted on 2015-07-23 15:06  Tonix  阅读(174)  评论(0编辑  收藏  举报