Header Ad

Leetcode Heaters problem solution

In this Leetcode Heaters problem solution Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.

Every house can be warmed, as long as the house is within the heater's warm radius range. 

Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses.

Notice that all the heaters follow your radius standard, and the warm radius will the same.

Leetcode Heaters problem solution


Problem solution in Python.

class Solution:
    def findRadius(self, houses: List[int], heaters: List[int]) -> int:
        
        nHeater = len(heaters)
        heaters.sort()
        maxDistance = - math.inf
        for house in houses:
            index = bisect_left(heaters, house)
            if index == 0:
                maxDistance = max(maxDistance, abs(house-heaters[index]))
            elif index == nHeater:
                maxDistance = max(maxDistance, abs(house-heaters[index-1]))
            else:
                maxDistance = max(maxDistance, min(abs(house-heaters[index-1]), abs(house-heaters[index])))
        return maxDistance

Problem solution in Java.

class Solution {
    public int findRadius(int[] houses, int[] heaters) {
        int[] array = new int[houses.length];
        int max = 0;
        Arrays.fill(array, Integer.MAX_VALUE);
        for(int i = 0; i < heaters.length; i++){
            int heat = heaters[i];
            for(int j = 0; j < houses.length; j++){
                if(houses[j] == heat){
                    array[j] = 0;
                }else{
                    array[j] = Math.min(array[j], Math.abs(houses[j] - heat));
                }
                
            }
        }
        Arrays.sort(array);
        return array[array.length - 1];
    }
}

Problem solution in C++.

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        sort(houses.begin(), houses.end());
        sort(heaters.begin(), heaters.end());
        int n=houses.size();
        int m=heaters.size();
        vector<int> a(n, INT_MAX);
        
        for(int i=0,j=0;i<n && j<m;){
            if(houses[i]<=heaters[j]){
                a[i]=heaters[j]-houses[i];
                i++;
            }
            else
                j++;
        }
        
        for(int i=n-1,j=m-1;i>=0 && j>=0;){
            if(houses[i]>=heaters[j]){
                a[i]=min(houses[i]-heaters[j],a[i]);
                i--;
            }
            else
                j--;
        }
        
        int ans=0;
        for(int i=0;i<n;i++)
            ans=max(ans,a[i]);
        return ans;
    }
};


Post a Comment

0 Comments