Easy to understand Java solution


  • 0
    public class Solution {
        public int findRadius(int[] houses, int[] heaters) {
            Arrays.sort(houses);
            Arrays.sort(heaters);
            int heaterIndex = 0;
            int min_radius = 0;
            for (int i = 0; i < houses.length; i++) {
                int housePos = houses[i];
                
                while (heaterIndex < heaters.length && heaters[heaterIndex] < housePos) {
                    heaterIndex++;
                }
                
                int min_distance = Integer.MAX_VALUE;
                if (heaterIndex < heaters.length) {
                    min_distance = Math.min(min_distance, Math.abs(heaters[heaterIndex] - housePos));
                }
                
                if (heaterIndex > 0) {
                    min_distance = Math.min(min_distance, Math.abs(heaters[heaterIndex - 1] - housePos));
                }
                min_radius = Math.max(min_radius, min_distance);
            }
            return min_radius;
        }
    }
    
    

Log in to reply
 

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