程式語言 - LeetCode - C++ - 475. Heaters



題目:


解答:

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        int ans = 0;

        sort(heaters.begin(), heaters.end());

        for (int h : houses) {
            int l = INT_MAX;
            int r = INT_MAX;
            auto it = lower_bound(heaters.begin(), heaters.end(), h);

            if (it != heaters.end()) {
                r = *it - h;
            }
            if (it != heaters.begin()) {
                l = h - *prev(it);
            }

            ans = max(ans, min(r, l));
        }

        return ans;
    }
};