File tree Expand file tree Collapse file tree 1 file changed +58
-11
lines changed Expand file tree Collapse file tree 1 file changed +58
-11
lines changed Original file line number Diff line number Diff line change @@ -66,17 +66,16 @@ https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days
66
66
``` python
67
67
def canShip (opacity ):
68
68
# 指定船的容量是否可以在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
80
79
```
81
80
82
81
## 关键点解析
@@ -85,6 +84,10 @@ return lo
85
84
86
85
## 代码
87
86
87
+ * 语言支持:` JS ` ,` Python `
88
+
89
+ ` python ` :
90
+
88
91
``` python
89
92
class Solution :
90
93
def shipWithinDays (self , weights : List[int ], D : int ) -> int :
@@ -115,6 +118,50 @@ class Solution:
115
118
return lo
116
119
```
117
120
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
+
118
165
## 扩展
119
166
120
167
## 参考
You can’t perform that action at this time.
0 commit comments