475. Heaters

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了475. Heaters相关的知识,希望对你有一定的参考价值。

java.util.Arrays.binarySearch() method
public static int binarySearch(int[] a, int key)
Parameters
* a ? This is the array to be searched.?
* key ? This is the value to be searched for.?

This method returns index of the search key, if it is contained in the array, else it returns (-(insertion point) - 1). The insertion point is the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.

https://www.geeksforgeeks.org/arrays-binarysearch-java-examples-set-1/

For each house, we apply binary search twice to find its left and right neighbor heaters to compute the radius for it to be covered. 

Find the left heater that is closest to him and the the right heater that is closest to him 








The idea is to leverage decent Arrays.binarySearch() function provided by Java.

1. For each house, find its position between those heaters (thus we need the heaters array to be sorted).
2. Calculate the distances between this house and left heater and right heater, get a MIN value of those two values. Corner cases are there is no left or right heater.
3. Get MAX value among distances in step 2. It‘s the answer.

Time complexity: max(O(nlogn), O(mlogn)) - m is the length of houses, n is the length of heaters.




class Solution {
    public int findRadius(int[] houses, int[] heaters) {
        Arrays.sort(heaters);
        int res = Integer.MIN_VALUE;
        
        for(int house : houses){
            int index = Arrays.binarySearch(heaters, house);
            // ? 
            if(index < 0){
                index = -(index + 1);
            }
            int dist1 = index - 1 >= 0 ? house - heaters[index - 1] : Integer.MAX_VALUE;
            int dist2 = index < heaters.length ? heaters[index] - house : Integer.MAX_VALUE;
            
            res = Math.max(res, Math.min(dist1, dist2));
        }
        return res;
        
    }
}

 

以上是关于475. Heaters的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 475. Heaters

475.Heaters java

LeetCode #475 Heaters

475. Heaters (start binary search, appplication for binary search)

leetcode 475. 供暖器(Heaters)

475. 供暖器