475. Heaters

QUESTION:

Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.

Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Note:

  1. Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
  2. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
  3. As long as a house is in the heaters’ warm radius range, it can be warmed.
  4. All the heaters follow your radius standard and the warm radius will the same.

Example 1:

Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

Example 2:

Input: [1,2,3,4],[1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.

EXPLANATION:

其实思路是比较简单的,就是找到所有房子最近的供热点,然后取所有的最大值作为半径。

那么思路就很简单了:

1.找到距离房子最近的供热点(二分法进行查找),并计算出最短半径。

2.求出所有最短半径的最大值就是最后的答案。

关键点就是二分法查找吧。具体可以看代码。

然后在看discuss的时候发现一个更为简单以及优雅的方式:

其实也是用的二分法进行查找,但是在之前就对house进行了排序,这样就可以确保i是顺着进行流动的。

关键点在于2 * house >= heaters[i] + heaters[i + 1],估计很多人不理解为啥,其实是house >= (heaters[i] + heaters[i + 1])/2,怎么样,这样是不是就是看出来了。

其实就是算出house离那个heater最近,然后算出距离就可以了。

SOLUTION:

public class Solution {
    public int findRadius(int[] houses, int[] heaters) {
        int result = -1;
        Arrays.sort(heaters);
        for(int i = 0;i<houses.length;i++){
            int house = houses[i];
            int search = findRadiusHelper(heaters,house);
            search = Math.abs(heaters[search] - houses[i]);
            result = Math.max(result,search);
        }
        return result;
    }
    public int findRadiusHelper(int[] heaters,int key){
        int low = 0,high = heaters.length-1;

        while (low<=high){
            int mid = (low + high) >>> 1;
            int midVal = heaters[mid];

            if (midVal < key){
                low = mid + 1;
            }else if (midVal > key){
                high = mid - 1;
            }else
                return mid; // key found
        }
        low = low>heaters.length-1?heaters.length-1:low;
        high = high<0?0:high;
        return Math.abs(key-heaters[low])-Math.abs(heaters[high]-key)>0?high:low;
    }
}

//更为优雅的方式:
public class Solution {
    public int findRadius(int[] houses, int[] heaters) {
        Arrays.sort(houses);
        Arrays.sort(heaters);
        int i = 0, res = 0;
        for(int house : houses){
            while(i < heaters.length - 1 && 2 * house >= heaters[i] + heaters[i + 1]) i++;
            res = Math.max(res, Math.abs(heaters[i] - house));
        }
        return res;
    }
}