Skip to content

Commit

Permalink
feat(js): add js solution for problem 1011 (azl397985856#332)
Browse files Browse the repository at this point in the history
* feat(js): add js solution for problem 1011

* Update 1011.capacity-to-ship-packages-within-d-days.md

Co-authored-by: lucifer <azl397985856@gmail.com>
  • Loading branch information
feikerwu and azl397985856 committed Apr 1, 2020
1 parent e77854d commit 50c9a89
Showing 1 changed file with 58 additions and 11 deletions.
69 changes: 58 additions & 11 deletions problems/1011.capacity-to-ship-packages-within-d-days.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,16 @@ https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days
```python
def canShip(opacity):
# 指定船的容量是否可以在D天运完
lo = 0
hi = total
while lo < hi:
mid = (lo + hi) // 2
if canShip(mid):
hi = mid
else:
lo = mid + 1

return lo

lo = 0
hi = total
while lo < hi:
mid = (lo + hi) // 2
if canShip(mid):
hi = mid
else:
lo = mid + 1

return lo
```

## 关键点解析
Expand All @@ -85,6 +84,10 @@ return lo

## 代码

* 语言支持:`JS``Python`

`python`:

```python
class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
Expand Down Expand Up @@ -115,6 +118,50 @@ class Solution:
return lo
```

`js`:

```js
/**
* @param {number[]} weights
* @param {number} D
* @return {number}
*/
var shipWithinDays = function(weights, D) {
let high = weights.reduce((acc, cur) => acc + cur)
let low = 0

while(low < high) {
let mid = Math.floor((high + low) / 2)
if (canShip(mid)) {
high = mid
} else {
low = mid + 1
}
}

return low

function canShip(opacity) {
let remain = opacity
let count = 1
for (let weight of weights) {
if (weight > opacity) {
return false
}
remain -= weight
if (remain < 0) {
count++
remain = opacity - weight
}
if (count > D) {
return false
}
}
return count <= D
}
};
```

## 扩展

## 参考

0 comments on commit 50c9a89

Please sign in to comment.