加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[Lintcode]183. Wood Cut

发布时间:2020-12-14 04:25:26 所属栏目:大数据 来源:网络整理
导读: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 lon

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为满足条件的情况 也有低级错误

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读