Arranging Coins(硬币排列)

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.(给你n枚硬币来组成一个阶梯形,这个阶梯每第k行必须包含k枚硬币)

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.

Example 1:
n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.

Example 2:
n = 8

The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤

Because the 4th row is incomplete, we return 3.

1.个人分析

从例子中观察分析可以看得出其中的求解规律,将输入的n不断进行减1,2,3…,直到n<=0为止。

2.个人解法

int arrangeCoins(int n) 
{
    int i;      
    for (i=1; n>0; ++i){
        n -= i;
    }
    if(n < 0)
        return i - 2;
    else
        return i - 1;
}

3.参考解法
(1)

int arrangeCoins(int n)
{
    if(n <= 1) return n;
    long left = 0, right = n;

    while(left <= right){
        long mid = left + (right - left)/2;
        long sum = ((1 + mid) * mid)/2;
        if(sum <= n){
            left = mid + 1;
        }else {
            right = mid - 1;
        }
    }

    return left - 1;
}

(2)

int arrangeCoins(int n)
{
     return sqrt(2 * (long)n + 1 / 4.0) - 1 / 2.0;
}

4.总结
第一种解法是最简单直接的方法,时间复杂度为O(n)(也有说是O(sqrt(n)));第二种则采用了二分查找的思路,时间复杂度为O(logn);第三种则是利用一元二次方程求根的数学方法求解,时间复杂度为O(1),但不明白为什么该问题与一元二次方程求根等价。

PS:

  • 题目的中文翻译是本人所作,如有偏差敬请指正。
  • 其中的“个人分析”和“个人解法”均是本人最初的想法和做法,不一定是对的,只是作为一个对照和记录。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值