harrytothemoon / leetcodeAplus

Leetcode meeting note
2 stars 0 forks source link

[849] Maximize Distance to Closest Person #22

Open tsungtingdu opened 3 years ago

tsungtingdu commented 3 years ago

two pointers

var maxDistToClosest = function(seats) {
    let max = 0
    let runner = 0
    let base = 0

    while (runner < seats.length) {

        // find the next base
        while (seats[base] === 1) {
            base++
            runner = base
        }

        if (seats[runner + 1] === 1 || runner + 1 === seats.length) {
            // edge case
            if (runner + 1 === seats.length || base === 0) {
                max = Math.max(runner - base + 1, max)
            } else {
                max = Math.max((runner - base + 2) >> 1, max)
            }
            runner++
            base = runner
        } else {
            runner++
        }
    }
    return max
};

JS 原生方法解

var maxDistToClosest = function(seats) {
    return seats.join('').split(1).reduce((acc, item, index, arr) => {
        let tempAcc = (index === 0 || index === arr.length - 1) ? item.length : (item.length + 1) >> 1
        return Math.max(acc, tempAcc)
    }, 0)
};
henry22 commented 3 years ago
harrytothemoon commented 3 years ago

把早上說的寫法完成

var maxDistToClosest = function(seats) {
    if (seats.length === 2) return 1
    return Math.max(...distance (seats), ...distance(seats.reverse()))

    function distance (nums) {
        let res = []
        let start = 0
        let end = 0
        let run = 0
        while (run < nums.length) {
           if (nums[run] === 1 && run !== nums.length - 1) {
               start = run
               end = run
               while (nums[run + 1] !== 1 && run + 1 !== nums.length - 1) {
                   run++
               }
               end = run + 1
               if (end === nums.length - 1 && nums[end] !== 1) res.push(end - start)
               else res.push((end - start) >> 1)
           }
            run++
        }
        return res       
    }
};