1. 程式人生 > >leetcode441. 排列硬幣

leetcode441. 排列硬幣

https://leetcode-cn.com/problems/arranging-coins/

你總共有 n 枚硬幣,你需要將它們擺成一個階梯形狀,第 k 行就必須正好有 k 枚硬幣。
給定一個數字 n,找出可形成完整階梯行的總行數。
n 是一個非負整數,並且在32位有符號整型的範圍內。
示例 1:
n = 5
硬幣可排列成以下幾行:
¤
¤ ¤
¤ ¤
因為第三行不完整,所以返回2.
示例 2:
n = 8
硬幣可排列成以下幾行:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
因為第四行不完整,所以返回3.

暴力法不可取:

class Solution:
    def arrangeCoins(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n <= 1:
            return n
        res, total = 0, 0
        for i in range(1,n+1):
            total += i
            if n - total < 0:
                return res
            res += 1

用數學方法,x(1+x)/2 <= n,求解可得x<=(-1+sqrt(8*n+1))//2:

import math

class Solution:
    def arrangeCoins(self, n):
        """
        :type n: int
        :rtype: int
        """
        return int((-1+math.sqrt(8*n+1))//2)

二分:

class Solution:
    def arrangeCoins(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n <= 1:
            return n
        left, right = 0, n
        while left <= right:
            mid = (left+right)//2
            if mid*(mid+1)/2 <= n:
                left = mid+1
            else:
                right = mid-1
        return left-1