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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

LintCode刷题笔记-- BackpackIV

LintCode刷题笔记-- BackpackII

LintCode刷题笔记-- LongestCommonSquence

LintCode刷题笔记-- Distinct Subsequences

LintCode刷题笔记--Longest Increasing Subsequence

LintCode刷题笔记-- Maximal Square