在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ The Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.) Example 1: Input: people = 3
Output: 1
Explanation: 1 boat (1, 2)
Example 2: Input: people = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)
Example 3: Input: people = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)
Note:
第 每艘船最多可同时载两人,但条件是这些人的重量之和最多为 返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
示例 1: 输入:people = [1,2], limit = 3 输出:1 解释:1 艘船载 (1, 2) 示例 2: 输入:people = [3,2,2,1], limit = 3 输出:3 解释:3 艘船分别载 (1, 2), (2) 和 (3) 示例 3: 输入:people = [3,5,3,4], limit = 5 输出:4 解释:4 艘船分别载 (3), (3), (4), (5) 提示:
664ms
1 class Solution { 2 func numRescueBoats(_ people: [Int], _ limit: Int) -> Int { 3 let people = people.sorted() 4 var left = 0, right = people.count - 1 5 var count = 0 6 while left <= right { 7 if people[left] + people[right] <= limit { 8 count += 1 9 left += 1 10 right -= 1 11 } else { 12 count += 1 13 right -= 1 14 } 15 } 16 return count 17 } 18 } Runtime: 708 ms
Memory Usage: 19.8 MB
1 class Solution { 2 func numRescueBoats(_ people: [Int], _ limit: Int) -> Int { 3 var people = people.sorted(by:<) 4 var ans:Int = 0 5 var hi:Int = people.count - 1 6 var lo:Int = 0 7 while (hi >= lo) 8 { 9 if people[lo] + people[hi] <= limit 10 { 11 lo += 1 12 } 13 hi -= 1 14 ans += 1 15 } 16 return ans 17 } 18 } 764ms 1 class Solution { 2 func numRescueBoats(_ people: [Int], _ limit: Int) -> Int { 3 var people = people.sorted() 4 var ans = 0, headIndex = 0, tailIndex = people.count - 1 5 while headIndex <= tailIndex { 6 ans += 1 7 var lastTailIndex = tailIndex 8 while tailIndex > headIndex { 9 if people[tailIndex]+people[headIndex] > limit { 10 tailIndex -= 1 11 if tailIndex == headIndex { 12 ans += (lastTailIndex - headIndex) 13 return ans 14 } 15 }else { 16 ans += (lastTailIndex - tailIndex) 17 tailIndex -= 1 18 break 19 } 20 } 21 headIndex += 1 22 } 23 return ans 24 } 25 }
|
请发表评论