Arranging Coins

题目地址:https://leetcode.com/problems/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.

题目理解起来还是比较容易的,就是看一下等差数列 1,2,3,4,......i 的和,等差数列前 i 项和公式:


Si=ia1+i(i1)2d

在本题目中,我们做的其实就是 a1=1 d=1 的情况,于是有:


Si=i(i+1)2

我们要确定的就是 Si 刚好小于硬币个数n时候的i,也就是等差数列的第i项,于是有:


Si<=n<Si+1


i(i+1)2<=n<(i+1)(i+2)2


i(i+1)<=2n<(i+1)(i+2)

于是我们代码可以这么写:

public class ArrangingCoins {
    public static int arrangeCoins(int n) {
        for (int i = 1; i < n; i++) {
            if ((i * (i + 1) <= 2 * n) && ((i + 1) * (i + 2) > 2 * n))
                return i;
            continue;
        }
        return 0;
    }

    public static void main(String[] args) {
        // 超时报错
        System.out.println(arrangeCoins(1804289383));
    }
}

可以看出,这个循环是从1开始的,如果n比较大的话,这个时间就玄乎了,有没有更快的方法呢?我们再看一下,现在知道了这个:


2n<(i+1)(i+2)


2n<i2+3i+2


2n+2<i2+4i+4=(i+2)2


2n+2<(i+2)2


i>2n+22

有了这个以后,那么我们前面的就不用算了,省的费那么多时间,于是代码实现为:

public class ArrangingCoins {
    public static int arrangeCoins(int n) {
        if (n <= 1)
            return n;
        int start = (int)Math.sqrt(n + 1) * (int)Math.sqrt(2) - 2;
        for (int i = start; i < n; i++) {
            if ((i * (i + 1) <= 2 * n) && ((i + 1) * (i + 2) > 2 * n))
                return i;
            continue;
        }
        return 0;
    }

    public static void main(String[] args) {
        System.out.println(arrangeCoins(1804289383));
    }
}

这回就快多了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值