自己写的:
import math class Solution: def arrangeCoins(self, n: int) -> int: # 计算判别式 discriminant = 1 + 8 * n # 计算根 root1 = (-1 + math.sqrt(discriminant)) / 2 # 返回地板取整后的根 return math.floor(root1)
二分法:
class Solution { public int arrangeCoins(int n) { long left = 1, right = n; while (left < right) { long mid = left + (right - left + 1) / 2; // 如果 mid 行硬币总数不超过 n,则将左边界移动到 mid,否则将右边界移动到 mid - 1 if (mid * (mid + 1) / 2 <= n) { left = mid; } else { right = mid - 1; } } // 最终 right 就是最大可放置硬币的阶梯行数 return (int) right; } }
标签:排列,硬币,int,mid,leedcode,right,math,left From: https://www.cnblogs.com/yyyjw/p/18168038