LeetCode 441. 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.

题意:给定n枚硬币,将n枚硬币组成阶梯形状,要求第k行正好有k枚硬币。
对给定的数量n,判断可以形成的完整阶梯的个数。
已知n是一个非负整数,并在32位有符号整数范围内。

没有想出很好的解决方法,直接判断的。

public int arrangeCoins(int n) {
        int step = 1;
        while(n >= step){
            n -= step;
            step++;
        }
        return step - 1;
    }

 

然后参考了LeetCode中的答案:https://leetcode.com/problems/arranging-coins/discuss/92274

方法二:

利用二分法,找出前i行之和刚好大于n的临界点,这样i - 1就是能排满的行数。
left = 1(第1行),right = n(第n行)。利用二分法找i,将mid看成i. mid = left + (right - left) / 2.
则利用等差数列求和公式,第mid行之和为:sum = (1 + mid) * mid / 2

public int arrangeCoins(int n) {
        if (n <= 1)
            return n;
        long left = 1, right = n;
        while (left <= right) {
            long mid = left + (right - left) / 2;
            if (mid * (mid + 1) / 2 <= n)
                left = mid + 1;
            else
                right = mid - 1;
        }
        return (int) left - 1;
    }

方法三:

利用等差数列求和的性质,前x项和为:n = (1 + x) * x / 2;
则可转换为:x2 + x - 2 * n = 0,根据一元二次方程的求根公式,可得x = Math.sqrt(1 + 8 * n) - 1) / 2
将n变成long类型是为了避免溢出的情况

public int arrangeCoins(int n) {
        return (int)(Math.sqrt(1 + 8 * (long)n) - 1) / 2;
    }

 

posted @ 2018-01-10 21:38  zeroingToOne  阅读(128)  评论(0编辑  收藏  举报