Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 50c9a89

Browse files
feat(js): add js solution for problem 1011 (azl397985856#332)
* feat(js): add js solution for problem 1011 * Update 1011.capacity-to-ship-packages-within-d-days.md Co-authored-by: lucifer <[email protected]>
1 parent e77854d commit 50c9a89

File tree

1 file changed

+58
-11
lines changed

1 file changed

+58
-11
lines changed

problems/1011.capacity-to-ship-packages-within-d-days.md

Lines changed: 58 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -66,17 +66,16 @@ https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days
6666
```python
6767
def canShip(opacity):
6868
# 指定船的容量是否可以在D天运完
69-
lo = 0
70-
hi = total
71-
while lo < hi:
72-
mid = (lo + hi) // 2
73-
if canShip(mid):
74-
hi = mid
75-
else:
76-
lo = mid + 1
77-
78-
return lo
79-
69+
lo = 0
70+
hi = total
71+
while lo < hi:
72+
mid = (lo + hi) // 2
73+
if canShip(mid):
74+
hi = mid
75+
else:
76+
lo = mid + 1
77+
78+
return lo
8079
```
8180

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

8685
## 代码
8786

87+
* 语言支持:`JS``Python`
88+
89+
`python`:
90+
8891
```python
8992
class Solution:
9093
def shipWithinDays(self, weights: List[int], D: int) -> int:
@@ -115,6 +118,50 @@ class Solution:
115118
return lo
116119
```
117120

121+
`js`:
122+
123+
```js
124+
/**
125+
* @param {number[]} weights
126+
* @param {number} D
127+
* @return {number}
128+
*/
129+
var shipWithinDays = function(weights, D) {
130+
let high = weights.reduce((acc, cur) => acc + cur)
131+
let low = 0
132+
133+
while(low < high) {
134+
let mid = Math.floor((high + low) / 2)
135+
if (canShip(mid)) {
136+
high = mid
137+
} else {
138+
low = mid + 1
139+
}
140+
}
141+
142+
return low
143+
144+
function canShip(opacity) {
145+
let remain = opacity
146+
let count = 1
147+
for (let weight of weights) {
148+
if (weight > opacity) {
149+
return false
150+
}
151+
remain -= weight
152+
if (remain < 0) {
153+
count++
154+
remain = opacity - weight
155+
}
156+
if (count > D) {
157+
return false
158+
}
159+
}
160+
return count <= D
161+
}
162+
};
163+
```
164+
118165
## 扩展
119166

120167
## 参考

0 commit comments

Comments
 (0)