Open tsungtingdu opened 3 years ago
夾在兩個1正中間的0,則最大距離為第二個1的index減去第一個0的index加1再除以二
/**
* @param {number[]} seats
* @return {number}
*/
var maxDistToClosest = function(seats) {
let res = 0
let pos = 0
const size = seats.length
for(let i = 0; i < size; i++) {
if(seats[i] === 1) {
if(pos === 0) {
res = Math.max(res, i)
} else {
res = Math.max(res, Math.floor((i - pos + 1) / 2))
}
pos = i + 1
}
}
res = Math.max(res, size - pos)
return res
};
把早上說的寫法完成
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
}
};
two pointers
JS 原生方法解
join('')
將陣列組合成字串split(1)
把所有包含0
的字串給拆出來成為陣列reduce
遍歷該陣列。頭尾的 items 回傳原本的長度,其他則回傳(item.length + 1) >> 1
acc
比較過後,將較大的值回傳到acc
當中reduce
之後的結果