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; } }