【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)。
相關文章
- Removing People 題解REM
- npm install -save 和 -save-devNPMdev
- npm –save-dev –save 的區別NPMdev
- canvas save()Canvas
- Save Water
- save download pdf
- They just wanted to find small ways to throw people
- Unable to save settings: Failed to save settings. Please restart PyCharm解決AIRESTPyCharm
- canvas save()和restore()CanvasREST
- docker tag save loadDocker
- save() create()區別
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- I do not even think it's a case of people loving PSO
- F. Magic Will Save the World
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- Kechuang People|ASF Director Wu Sheng: A Handbook for the Growth of Buddhist Programmers
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1218. Number Complement
- 【Lintcode】1850. Pick ApplesAPP