zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    方法中的散列可变参数
    方法中的散列可变参数
    策略模式
    策略模式
    HashSet,TreeSet
    HashSet,TreeSet
    ArrayList和LinkedList
    ArrayList和LinkedList
    关于鼠标悬浮标签元素效果(CSS:cursor属性)
    关于鼠标悬浮标签元素效果(CSS:cursor属性)
  • 原文地址:https://www.cnblogs.com/tonix/p/4670542.html
Copyright © 2011-2022 走看看