8-line C++ Binary Search Solution, std::lower_bound


  • 0
    class Solution {
    public:
        int findRadius(vector<int>& houses, vector<int>& heaters) {
            sort(heaters.begin(), heaters.end());
            int ans = 0;
            for (auto h : houses) {
                auto ge = lower_bound(heaters.begin(), heaters.end(), h); // www.cplusplus.com/reference/algorithm/lower_bound
                if(*ge-h) // should be if(ge==heaters.end()||*ge-h)
                    ans = max(ans, min(  ge!=heaters.end()?*ge-h:INT_MAX  ,  ge!=heaters.begin()?h-*prev(ge,1):INT_MAX  ));
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.