1. 程式人生 > >849. Maximize Distance to Closest Person

849. Maximize Distance to Closest Person

題目

In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.

There is at least one empty seat, and at least one person sitting.

Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.

Return that maximum distance to closest person.

Example 1:

Input: [1,0,0,0,1,0,1] Output: 2 Explanation: If Alex sits in the second open seat (seats[2]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. Example 2:

Input: [1,0,0,0] Output: 3 Explanation: If Alex sits in the last seat, the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. Note:

1 <= seats.length <= 20000 seats contains only 0s or 1s, at least one 0, and at least one 1.

思路

基本思路就是從左往右遍歷,找標為1的seat,求跟上一個1之間的距離,首尾不用除2,中間都要除以2,然後取一個最大值。

程式碼

class Solution {
public:
    int maxDistToClosest(vector<int>& seats) {
        int max = 0;
        int lastpos = -1;
        int
curlen; for(int ipos = 0; ipos < seats.size(); ipos++){ if(seats[ipos] != 0){ if(lastpos < 0) curlen = ipos; else curlen = (ipos-lastpos)>>1; lastpos = ipos; if(curlen > max) max = curlen; } } if(seats.size()-1-lastpos > max) max = seats.size()-1-lastpos; return max; } };

結果

79 / 79 個通過測試用例 狀態:通過 執行用時:12 ms 結果裡有人8ms就跑完了,想了半天沒想出怎麼優化程式碼,最後還是看答案了。 答案的基本思路跟我相同,但在計算上做了一些優化,最左邊的部分單獨分離出一個while迴圈,加入了一個計算長度的變數cnt,用cnt++來統計seat之間的間隔。

感想

好像之前做過一道類似的題,比這道題更難一些。當時似乎是會有很多人逐個找座位,我的思路是用連結串列來儲存各個間隔。