JavaScript刷LeetCode -- 904. Fruit Into Baskets
一、題目
In a row of trees, the i-th tree produces fruit with type tree[i].
You start at any tree of your choice, then repeatedly perform the following steps:
Add one piece of fruit from this tree to your baskets. If you cannot, stop.
Move to the next tree to the right of the current tree. If there is no tree to the right, stop.
Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.
You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.
What is the total amount of fruit you can collect with this procedure?
二、題目大意
找出陣列tree中最長的子陣列,並且子陣列中只含有兩個不同的元素。
三、解題思路
理解題目之後,思路還是很簡單的:遍歷陣列,記錄只含有兩個元素的子陣列的長度,當子陣列不滿足要求時,向前遍歷找出下一個子陣列的起始點。
四、程式碼實現
const totalFruit = tree => { const max = tree.length const s = new Set() let ans = Number.MIN_SAFE_INTEGER let sum = 0 for (let i = 0; i < max; i++) { const type = tree[i] if (s.size < 2) { s.add(type) sum++ continue } if (s.has(type)) { sum++ } else { ans = Math.max(ans, sum) let start = i - 1 while (start > 0) { const cur = tree[start] const pre = tree[start - 1] if (cur === pre) { start-- } else { break } } sum = i - start + 1 s.clear() s.add(type) s.add(tree[i - 1]) } } ans = Math.max(ans, sum) return ans }
對於向前迴圈尋找下一個子陣列的起始點還可以優化一下,這樣時間複雜度就可以達到O(n):
const totalFruit1 = tree => {
const max = tree.length
const s = new Set()
let ans = Number.MIN_SAFE_INTEGER
let sum = 0
// 維護下一個子陣列的起始節點
let start = 0
for (let i = 0; i < max; i++) {
const type = tree[i]
if (s.size < 2) {
s.add(type)
sum++
start = i
continue
}
if (s.has(type)) {
sum++
if (type !== tree[i - 1]) {
start = i
}
} else {
ans = Math.max(ans, sum)
sum = i - start + 1
s.clear()
s.add(type)
s.add(tree[i - 1])
start = i
}
}
ans = Math.max(ans, sum)
return ans
}
如果本文對您有幫助,歡迎關注我的微信公眾號【超愛敲程式碼】,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。