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

LintCode刷题笔记(九章ladder PartOne)--BugFree

时间:2017-05-21 13:41:52      阅读:709      评论:0      收藏:0      [点我收藏+]

标签:lintcode   enum   blog   maximum   sea   pie   end   one   with   

  • 九章ladder的前半部分刷题笔记,在这次二刷的时候补上~

@ 2017.05.21

141 - sqrtx

二分答案  

---  binarySearch二分法 ---

class Solution:
    """
    @param x: An integer
    @return: The sqrt of x
    """
    def sqrt(self, x):
        # write your code here
        if not x:
            return 0
        start, end = 1, x
        while start < end - 1:
            mid = (end - start) / 2 + start
            val = mid ** 2
            if val < x:
                start = mid
            elif val == x:
                return mid
            else:
                end = mid
        if end ** 2 <= x:
            return end
        return start

14 - first-position-of-target

--- BinarySearch二分法 ---

class Solution:
    # @param nums: The integer array
    # @param target: Target number to find
    # @return the first position of target in nums, position start from 0 
    def binarySearch(self, nums, target):
        # write your code here
        if not nums:
            return
        start, end = 0, len(nums) - 1
        while start < end - 1:
            mid = (end - start) / 2 + start
            if nums[mid] < target:
                start = mid
            else:
                end = mid
        if nums[start] == target:
            return start
        if nums[end] == target:
            return end
        return -1

 183 - wood-cut

二分答案 

--- BinarySearch二分法 ---

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
        if not L or sum(L) < k:
            return 0
        start, end = 1, max(L)
        while start < end - 1:
            mid = (end - start) / 2 + start
            pieceNum = sum([ele / mid for ele in L])
            if pieceNum < k:
                end = mid
            else:
                start = mid
        if sum([ele / end for ele in L]) >= k:
            return end
        if sum([ele / start for ele in L]) >= k:
            return start

 

LintCode刷题笔记(九章ladder PartOne)--BugFree

标签:lintcode   enum   blog   maximum   sea   pie   end   one   with   

原文地址:http://www.cnblogs.com/wttttt/p/6884473.html

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