1. 程式人生 > >leetcode (Heaters)

leetcode (Heaters)

Title:Hearter     475

Difficulty:Easy

原題leetcode地址:  https://leetcode.com/problems/heaters/

 

1.  基本的一次遍歷

時間複雜度:O(n^2),巢狀迴圈。

空間複雜度:O(n),沒有申請額外空間。

    /**
     * 如果只有一間房屋,需要找到:左側最近的heater位於這個房屋的距離和右側最近的heater位於這個房屋的距離,對每一個房屋進行左右側進行查詢
     * @param houses
     * @param heaters
     * @return
     */
    public static int findRadius(int[] houses, int[] heaters) {

        Arrays.sort(houses);
        Arrays.sort(heaters);

        int i = 0;
        int radius = 0;

        for (int house : houses) {
            while (i < heaters.length - 1 && house > heaters[i]) {
                i++;
            }
            if (i != 0) {
                radius = Math.max(radius, Math.min(house - heaters[i - 1], Math.abs(house - heaters[i])));
            }
            else {
                radius = Math.max(Math.abs(house - heaters[0]), radius);
            }
        }

        return radius;

    }