分配硬币 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.

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.

解决:

① 按照第i行会有i个硬币分配,当n<0时,停止计数即可。55ms

public class Solution {
    public int arrangeCoins(int n) {
        int i = 1;
        int count = 0;
        while(n > 0){
            n = n - i;
            i ++;
            if(n >= 0){
                count ++;
            }
        }
        return count;
    }
}
② 采用折半查找的方式:46ms

我们要找到满足以下条件的x:
1 + 2 + 3 + 4 + 5 + 6 + 7 + ... + x <= n
即sum_{i=1}^x i <= n (i从1到x求和)
对它进行简化求和可以得到(x * ( x + 1)) / 2 <= n
在这种情况下,使用
折半查找来慢慢缩小满足方程的x的范围

public class Solution {
    public int arrangeCoins(int n) {
        int start = 0;
        int end = n;
        while (start <= end){
            int mid = (end - start) / 2 + start; //(end - start) / 2 + start  VS  (start + end) >>> 1
            if ((0.5 * mid * mid + 0.5 * mid ) <= n){//公式
                start = mid + 1;
            }else{
                end = mid - 1;
            }

        }
        return start - 1;
    }
}

③ 利用一元二次方程求根的数学方法求解:47ms

我们已知:
1 + 2 + 3 + 4 + 5 + 6 + 7 + ... + x <= n
即sum_{i=1}^x i <= n
求和可得(x * ( x + 1)) / 2 <= n
利用一元二次方程求根公式可得:
x = 1 / 2 * (-sqrt(8 * n + 1)-1)(为负数,不符合题意) 
或 x = 1 / 2 * (sqrt(8 * n + 1)-1)

public class Solution {
    public int arrangeCoins(int n) {//(int)((sqrt(1 + 8 * (long)n)-1) / 2)
        return (int) ((Math.sqrt(1 + 8.0 * n) - 1) / 2);// java会将中间结果自动装箱为long型数据
    }
}

转载于:https://my.oschina.net/liyurong/blog/1036965

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值