leetcode441. 排列硬币

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/85801901

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

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/85801901