[leetcode]: 441. Arranging Coins

太过爱你忘了你带给我的痛 2022-06-15 06:15 233阅读 0赞

1.题目

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

Given n, find the total number of full staircase rows that can be formed.

n is a non-negative integer and fits within the range of a 32-bit signed integer.
给n个硬币拼一个阶梯形状。第一行1个,第二行2个,第k行k个。问可以拼成一个几行的阶梯。
Example 1:
n = 5
¤
¤ ¤
¤ ¤
Because the 3rd row is incomplete, we return 2。拼成一个2行的阶梯

Example 2:
n = 8
¤
¤ ¤
¤ ¤ ¤
¤ ¤
Because the 4th row is incomplete, we return 3。拼成一个3行的阶梯。

2.分析

k行阶梯的硬币数为1+2+..+k=k*k+k<=2n
要求解这个k的大小。有两种方法。
方法1:数学方法求解。
k*k+k+1/4<=2n
(k+1/2)^2<=(2n+1/4)
k<=sqrt(2n+1/4)-1/2。
k 向下取整即可。
方法2:遍历或者二分查找。
已知k的范围为1-n,通过遍历或者二分查找找到最大的k满足k*k+k<=2n即可。

3.代码

方法1:

  1. int arrangeCoins(int n) {
  2. return floor(sqrt((double)2 * n + 0.25) - 0.5);
  3. }

方法2:

  1. class Solution {
  2. public:
  3. int arrangeCoins(int n) {
  4. if (n <= 1)
  5. return n;
  6. long long m = n;//避免溢出,统一转换成long long
  7. m *= 2;
  8. long long start = 1;
  9. long long end = n;
  10. while (start <= end) {
  11. long long mid = start + (end - start) / 2;
  12. if (mid*mid + mid <= m)
  13. start = mid + 1;
  14. else
  15. end = mid - 1;
  16. }
  17. return start - 1;
  18. }
  19. };

发表评论

表情:
评论列表 (有 0 条评论,233人围观)

还没有评论,来说两句吧...

相关阅读