【Lintcode】1601. Boats to Save People
題目地址:
https://www.lintcode.com/problem/boats-to-save-people/description
給定一個正整數列表 A A A,表示每個人的重量。再給一個數 l l l表示每艘船可以承載的最大重量。每艘船最多載兩人。問至少需要多少搜船才能把所有人都載完。
先排序,然後用對撞雙指標,設開的兩個指標分別是 i i i和 j j j並且 i < j i<j i<j,則先看 A [ j ] A[j] A[j]是否能與 A [ i ] A[i] A[i]同船,如果能,則同船,並將 i i i右移將 j j j左移;否則 A [ j ] A[j] A[j]要單獨坐船,則只將 j j j左移。相遇的時候,還要將剩下的那個人單獨坐船。程式碼如下:
import java.util.List;
public class Solution {
/**
* @param people: The i-th person has weight people[i].
* @param limit: Each boat can carry a maximum weight of limit.
* @return: Return the minimum number of boats to carry every given person.
*/
public int numRescueBoats(List<Integer> people, int limit) {
// Write your code here.
people.sort((p1, p2) -> Integer.compare(p1, p2));
int res = 0, i = 0, j = people.size() - 1;
while (i < j) {
if (people.get(i) + people.get(j) <= limit) {
i++;
}
j--;
res++;
}
// 如果i == j說明還剩下一個單獨的人,他自己坐船
return res + (i == j ? 1 : 0);
}
}
時間複雜度 O ( n log n ) O(n\log n) O(nlogn), n n n是人數,空間 O ( 1 ) O(1) O(1)。
相關文章
- npm install -save 和 -save-devNPMdev
- npm –save-dev –save 的區別NPMdev
- Removing People 題解REM
- canvas save()Canvas
- Why Do People Commit Suicide?MITUIIDE
- save() create()區別
- canvas save()和restore()CanvasREST
- save download pdf
- Unable to save settings: Failed to save settings. Please restart PyCharm解決AIRESTPyCharm
- docker tag save loadDocker
- F. Magic Will Save the World
- Ten Principles of Economics__How People Interact
- Day 008 IS abducted 400 people from a city in Syria
- 比德《英吉利教會史》(Ecclesiastical History of the English People)AST
- Laravel Lego :Save you from CRUDLaravelGo
- Save and Edit a Report Specification locally
- Ten Principles of Economics__How People Make Decisions
- Unable to save settings: Failed to save settings. Please restart IntelliJ IDEA 解決方案AIRESTIntelliJIdea
- FMDB使用SQLite事務Save PointSQLite
- iptables-save中文手冊(轉)
- I do not even think it's a case of people loving PSO
- Book People Mailing List的告別信AI
- Book People Mailing List 宣佈關閉AI
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- Idea報錯“Unable to save settings: Failed to save settings. Please restart IntelliJ IDEA”IdeaAIRESTIntelliJ
- Linux基礎命令---iptables-saveLinux
- 儲存載入模型model.save()模型
- Entity Framework 6.0 Tutorials(2):Async query and SaveFramework
- Django模型中的save方法 精講Django模型
- [LintCode] Permutation in String
- LintCode 主元素 II
- LintCode 解碼方法
- LintCode-Search for a Range
- LintCode-K Sum
- LintCode-Word SegmentationSegmentation