clueless coding // TODO: be smarter

LeetCode Heaters: CPP Solution



TL;DR Code Solution



int search(vector<int>& heaters, int target) {
    int left = 0;
    int right = heaters.size() - 1;

    while (left <= right) {
        int middle = (left + right) / 2;
        if (heaters[middle] == target) {
            return middle;
        }
        else if (heaters[middle] < target) {
            left = middle + 1;
        }
        else {
            right = middle - 1;
        }
    }
    return left;
}


int findRadius(vector<int>& houses, vector<int>& heaters) {
    int res = 0;

    sort(heaters.begin(), heaters.end(), [](int& a, int& b) {
        return a < b;
    });

    for (int i = 0; i < houses.size(); i++) {

        int curHouse = houses[i];

        int index = search(heaters, curHouse);

        int right = index == heaters.size() ? INT_MAX : abs(heaters[index] - curHouse);
        int left = index == 0 ? INT_MAX : abs(curHouse - heaters[index - 1]);

        res = max(res, min(left, right));
    }
    return res;
}