首页 > 代码库 > LintCode刷题笔记(九章ladder PartOne)--BugFree

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

  • 九章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