码迷,mamicode.com
首页 > 其他好文 > 详细

475. Heaters

时间:2018-11-08 18:13:41      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:his   length   org   sea   insert   dea   poi   search   UNC   

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

标签:his   length   org   sea   insert   dea   poi   search   UNC   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9929866.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!