Try   HackMD

Leetcode 849. Maximize Distance to Closest Person

tags: Leetcode(JAVA)

題目 : https://leetcode.com/problems/maximize-distance-to-closest-person/

想法 :

​​​​分成3種Case來看 :
​​​​1. 兩個1夾住的
​​​​2. 右方有1
​​​​3. 左方有1

時間複雜度 : O(n)。

程式碼 : (JAVA)

class Solution {
    public int maxDistToClosest(int[] seats) {
        int l=seats.length, where=0, ans=0, first=1;
        
        for(int i=0 ; i<l ; i++){
            if(first == 1 && seats[i] == 1){
                first=0;
                ans=Math.max(ans, i-where);
                where=i;
                continue;    
            }
            
            if(seats[i] == 1){
                ans=Math.max(ans, (i-where)/2);
                where=i;
            }
        }
        
        if(seats[l-1] == 0){
            //System.out.printf("%d %d", l, where);
            ans=Math.max(ans, l-1-where);
        }
        
        return ans;
    }
}