Skip to content

feat: add java solution to lc problem: 1011. Capacity To Ship Packages Within D Days #547

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,38 @@
<!-- 这里可写当前语言的特殊实现逻辑 -->

```java

class Solution {
public int shipWithinDays(int[] weights, int days) {
int left = 1, right = Integer.MAX_VALUE;
while (left < right) {
int mid = (left + right) >> 1;
if (canCarry(weights, days, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}


public boolean canCarry(int[] weights, int days, int carry) {
int useDay = 1;
int curCarry = 0;
for (int weight : weights) {
if (weight > carry) {
return false;
}
if ((carry - curCarry) >= weight) {
curCarry += weight;
} else {
curCarry = weight;
useDay++;
}
}
return useDay <= days;
}
}
```

### **...**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,38 @@ Note that the cargo must be shipped in the order given, so using a ship of capac
### **Java**

```java

class Solution {
public int shipWithinDays(int[] weights, int days) {
int left = 1, right = Integer.MAX_VALUE;
while (left < right) {
int mid = (left + right) >> 1;
if (canCarry(weights, days, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}


public boolean canCarry(int[] weights, int days, int carry) {
int useDay = 1;
int curCarry = 0;
for (int weight : weights) {
if (weight > carry) {
return false;
}
if ((carry - curCarry) >= weight) {
curCarry += weight;
} else {
curCarry = weight;
useDay++;
}
}
return useDay <= days;
}
}
```

### **...**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Solution {
public int shipWithinDays(int[] weights, int days) {
int left = 1, right = Integer.MAX_VALUE;
while (left < right) {
int mid = (left + right) >> 1;
if (canCarry(weights, days, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}


public boolean canCarry(int[] weights, int days, int carry) {
int useDay = 1;
int curCarry = 0;
for (int weight : weights) {
if (weight > carry) {
return false;
}
if ((carry - curCarry) >= weight) {
curCarry += weight;
} else {
curCarry = weight;
useDay++;
}
}
return useDay <= days;
}
}