码迷,mamicode.com
首页 > 其他好文 > 详细

[Lintcode]183. Wood Cut

时间:2019-02-10 09:17:21      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:@param   while   des   amp   14.   pie   nlog   for   oat   

183. Wood Cut

  • 本题难度: Hard
  • Topic: Binary Search

    Description

    Given n pieces of wood with length L[i] (integer array). Cut them into small pieces to guarantee you could have equal or more than k pieces with the same length. What is the longest length you can get from the n pieces of wood? Given L & k, return the maximum length of the small pieces.

Example
For L=[232, 124, 456], k=7, return 114.

Challenge
O(n log Len), where Len is the longest length of the wood.

Notice
You couldn‘t cut wood into float length.

If you couldn‘t get >= k pieces, return 0.

我的代码

class Solution:
    """
    @param L: Given n pieces of wood with length L[i]
    @param k: An integer
    @return: The maximum length of the small pieces
    """
    def woodCut(self, L, k):
        # write your code here
     # write your code here
        if L == []:
            return 0
        L.sort()
        max = L[-1]
        l = 1
        r = L[-1]
        while(l<=r):
            count = 0
            m = (l + r) // 2
            print(l,r,m)
            for i in L:
                count += i//m
            if count>=k:
                l = m+1
            else:
                r = m-1
        #1.边界问题,最后结果可能是从右向左逼近,此时m为第一个不满足条件的情况,反之,从左往右逼近,则m为满足条件的情况
        print(m)
        count = 0
        for i in L:
            count += i//m
        print(count)
        if count >= k:
            return m
        else:
            return m-1

思路

  1. 切割的大小肯定小于最长木料长度,而从最长木料选择截取特定长的的时间复杂度是log(L)
  2. 共有n块木料,每个特定的长度要试n次
  • 时间复杂度: nlog(L) L为最长木料长度
  • 出错
    想得挺顺利的,就是一个边界问题没考虑好,最后结果可能是从右向左逼近,此时m为第一个不满足条件的情况,反之,从左往右逼近,则m为满足条件的情况
    也有低级错误

[Lintcode]183. Wood Cut

标签:@param   while   des   amp   14.   pie   nlog   for   oat   

原文地址:https://www.cnblogs.com/siriusli/p/10358600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!