Java Binary Search Solution using templet


  • 0
    P
    public int findRadius(int[] houses, int[] heaters) {
            Arrays.sort(heaters);
            int res = 0; 
            for (int house : houses) {
                int start = 0;
                int end = heaters.length - 1;
                while (start + 1 < end) {
                    int mid = start + (end - start) / 2;
                    if (heaters[mid] == house) {
                        start = mid;
                    } else if (heaters[mid] < house) {
                        start = mid;     
                    } else {
                        end = mid; 
                    }
                }
                int dis1 = Math.abs(heaters[start] - house);
                int dis2 = Math.abs(heaters[end] - house);
                res = Math.max(res, Math.min(dis1, dis2)); 
            }
            return res; 
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.