在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Koko loves to eat bananas. There are Koko can decide her bananas-per-hour eating speed of Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer Example 1: Input: piles = 8
Output: 4
Example 2: Input: piles = 5
Output: 30
Example 3: Input: piles = 6
Output: 23
Note:
珂珂喜欢吃香蕉。这里有 珂珂可以决定她吃香蕉的速度 珂珂喜欢慢慢吃,但仍然想在警卫回来前吃掉所有的香蕉。 返回她可以在 示例 1: 输入: piles = [3,6,7,11], H = 8 输出: 4 示例 2: 输入: piles = [30,11,23,4,20], H = 5 输出: 30 示例 3: 输入: piles = [30,11,23,4,20], H = 6 输出: 23 提示:
340ms 1 class Solution { 2 func minEatingSpeed(_ piles: [Int], _ H: Int) -> Int { 3 var minSpeed = 1, maxSpeed = 1000_00 4 while minSpeed < maxSpeed { 5 let speed = (maxSpeed + minSpeed) / 2 6 if possible(piles, speed, H) { maxSpeed = speed } 7 else { minSpeed = speed + 1} 8 } 9 return minSpeed 10 } 11 12 func possible(_ piles: [Int], _ speed: Int, _ H: Int) -> Bool { 13 var time = 0 14 for p in piles { time += (p-1)/speed + 1 } 15 return H >= time 16 } 17 } Runtime: 420 ms
Memory Usage: 19.1 MB
1 class Solution { 2 func minEatingSpeed(_ piles: [Int], _ H: Int) -> Int { 3 var l:Int = 1 4 var r:Int = 1000_000_000 5 while (l < r) 6 { 7 var m:Int = (l + r) / 2 8 var total:Int = 0 9 for p in piles 10 { 11 total += (p + m - 1) / m 12 } 13 if total > H 14 { 15 l = m + 1 16 } 17 else 18 { 19 r = m 20 } 21 } 22 return l 23 } 24 } 444ms 1 class Solution { 2 func minEatingSpeed(_ piles: [Int], _ H: Int) -> Int { 3 guard piles.count > 0 else { 4 return 0 5 } 6 var r = piles.max()! + 1 7 if piles.count == H { 8 return r - 1 9 } 10 var l = 1 11 while l < r { 12 let m = l + (r - l) / 2 13 ///get how many hours using m 14 var hours = 0 15 for p in piles { 16 hours += (p + m - 1) / m 17 } 18 if hours <= H { 19 r = m 20 } else { 21 l = m + 1 22 } 23 } 24 return l 25 } 26 } 456ms 1 class Solution { 2 func isGood(_ piles: [Int], _ H: Int, _ K: Int) -> Bool { 3 var total = 0 4 for item in piles { 5 if item % K == 0 { 6 total = total + item / K 7 } else { 8 total = total + item / K + 1 9 } 10 if total > H { 11 return false 12 } 13 } 14 return true 15 } 16 17 func minEatingSpeed(_ piles: [Int], _ H: Int) -> Int { 18 if piles.count == 0 || H <= 0{ 19 return 0 20 } 21 22 var end = piles[0] 23 for item in piles { 24 end = max(end, item) 25 } 26 27 var begin = 1 28 while(begin<=end){ 29 let middle = (begin+end)/2 30 if isGood(piles, H, middle) { 31 end = middle - 1 32 } else { 33 begin = middle + 1 34 } 35 } 36 return begin 37 } 38 }
|
请发表评论