Leetcode刷题记录——441. 排列硬币

Leetcode刷题记录——441. 排列硬币_第1张图片
二分

class Solution:
    def __init__(self):
        self.d = {}
    def arrangeCoins(self, n: int) -> int:
        if n == 0:
            return 0
        if n == 1:
            return 1
        elif n == 3:
            return 2
        start = 0
        end = n // 2
        while start < end:
            mid = start + ((end-start)>>1)
            print(mid)
            if self.func(mid) <= n and self.func(mid +1) >n :
                return mid
            elif self.func(mid) > n:
                end = mid
            elif self.func(mid) < n:
                start = mid + 1
        return start
    def func(self,x):
        if x in self.d:
            return self.d[x]
        else:
            self.d[x] = x*(x+1)//2
        return self.d[x]

你可能感兴趣的:(leetcode,python编程技巧)