475. Heaters 加熱範圍

[抄題]:算法

Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.數據結構

Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.ide

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.優化

Note:spa

  1. Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
  2. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
  3. As long as a house is in the heaters' warm radius range, it can be warmed.
  4. All the heaters follow your radius standard and the warm radius will the same.

 

Example 1:debug

Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

 

Example 2:3d

Input: [1,2,3,4],[1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.

 [暴力解法]:code

時間分析:blog

空間分析:input

 [優化後]:

時間分析:

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

[思惟問題]:

the straight-forward check whether the next heater is closer than the current. Then I thought I probably don't need abs if I just use
    while heaters[i+1] - x <= x - heaters[i]:更
That's obviously correct if x is between the heaters, because then that's the correct distances of x to the two heaters. Less obviously (but imho not surprisingly) it's also correct if x isn't between them. Finally, after rewriting it to
    while heaters[i] + heaters[i+1] <= 2 * x

[一句話思路]:

頭回見 不知道什麼纔是「覆蓋所有」的最小距離:

每一個house都取最小距離求並集(最大距離)便可

[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):

[畫圖]:

[一刷]:

  1. 大小順序不肯定的距離 要加絕對值,別忘了
  2. i 更新爲 i +1以後變大了,此時用i。不用原來的i+ 1

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分鐘肉眼debug的結果]:

[總結]:

[複雜度]:Time complexity: O(n) Space complexity: O(1)

[英文數據結構或算法,爲何不用別的數據結構或算法]:

更新以後用i 

for (int house : houses) {
            while (i < heaters.length - 1 && heaters[i + 1] + heaters[i] <= 2 * house) {
                i++;
            }
            res = Math.max(res, Math.abs(heaters[i] - house));
        }

[關鍵模板化代碼]:

[其餘解法]:

[Follow Up]:

[LC給出的題目變變變]:

 [代碼風格] :

class Solution {
    public int findRadius(int[] houses, int[] heaters) {
        //ini: sort
        Arrays.sort(houses);
        Arrays.sort(heaters);
        int res = Integer.MIN_VALUE, i = 0;
        
        //update
        for (int house : houses) {
            while (i < heaters.length - 1 && heaters[i + 1] + heaters[i] <= 2 * house) {
                i++;
            }
            res = Math.max(res, Math.abs(heaters[i] - house));
        }
        
        return res;
    }
}
View Code
相關文章
相關標籤/搜索