LeetCode "Search a 2D Matrix II"

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 smartershorter solution: https://leetcode.com/discuss/47528/c-with-o-m-n-complexity

原文地址:https://www.cnblogs.com/tonix/p/4670542.html