路燈 -- 2016網易筆試題

 

題目:java

 一條長l的筆直的街道上有n個路燈,若這條街的起點爲0,終點爲l,第i個路燈座標爲ai,每盞燈能夠覆蓋到的最遠距離爲d,爲了照明需求,全部燈的燈光必須覆蓋整條街,可是爲了省電,要是這個d最小,請找到這個最小的d。數組

 

輸入描述:spa

每組數據第一行兩個整數n和l(n大於0小於等於1000,l小於等於1000000000大於0)。第二行有n個整數(均大於等於0小於等於l),爲每盞燈的座標,多個路燈能夠在同一點。code

 

輸出描述:orm

輸出答案,保留兩位小數。blog

 

輸入例子:排序

7 15
15 5 3 7 9 14 0rem

 

輸出例子:get

2.50string

 

思路:這題只要把起點和終點都加入第二行進行排序,而後求出最大相鄰的差值D,所求d=D/2;注意保留2位小數輸出,將求出double保留2位小數的一種方法爲

         String remain_d = String.format("%.2f", original_d);

下面是java代碼實現:

 1 package ustb.wangyi;
 2 import java.util.Arrays;
 3 
 4 public class StreetLamp {
 5     
 6     public static String getMinLightDist(int lampNum, int streetLen, int[] lampCoord) {
 7     
 8         if (lampNum <= 0 || lampNum > 1000) {
 9             throw new RuntimeException("街道燈的個數不符合要求");
10         }
11         
12         if (streetLen <= 0 || streetLen > 1000000000) {
13             throw new RuntimeException("街道的長度不符合要求");
14         }
15     
16         if (lampNum != lampCoord.length) {
17             throw new RuntimeException("數組中燈的個數與輸入的燈的個數不一致");
18         }
19         
20         for (int i = 0; i < lampCoord.length - 1; i++) {
21             if (lampCoord[i] < 0 || lampCoord[i] > streetLen) {
22                 throw new RuntimeException("數組中第" + i + "個燈的座標不符合要求");
23             }
24         }
25         
26         
27         Arrays.sort(lampCoord);
28         int maxAdjaDist = lampCoord[1] - lampCoord[0]; //初始化燈的最大相鄰距離
29         
30         for (int i = 1; i < lampCoord.length - 1; i++) {
31             int temp = lampCoord[i+1] - lampCoord[i];
32             if (temp > maxAdjaDist)
33                 maxAdjaDist = temp;
34         }
35         
36         //計算第一盞燈與街道起點的距離 和街道終點與最後一盞燈的距離
37         int temp1 = lampCoord[0] - 0;
38         int temp2 = streetLen - lampCoord[lampCoord.length - 1];
39         maxAdjaDist = Math.max(maxAdjaDist, temp1);
40         maxAdjaDist = Math.max(maxAdjaDist, temp2);
41     
42         double d = (double) maxAdjaDist / 2.0;
43         String s =String.format("%.2f", d);
44         return s;
45     
46     }
47     
48     public static void main(String[] args) {
49         
50         int[] lampCoord = {15, 5, 3, 7, 9, 14, 0};
51         int streetLen = 15;
52         int lampNum = 7;
53         String d = getMinLightDist(lampNum, streetLen, lampCoord);
54         System.out.println(d);
55     }
56     
57 
58 }
相關文章
相關標籤/搜索