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

方法一:牛頓迭代法。

public class Solution {
    private double f(double x, int n) {
        return x * (1 + x) / 2 - n;
    }
    private double derative(double x) {
        return x + 0.5;
    }
    public int arrangeCoins(int n) {
        double x = 0;
        while (true) {
            double nx = x - f(x, n) / derative(x);
            
            if (Math.abs(nx - x) < 0.01) break;
            x = nx;
        }
        return (int)x;
    }
}

方法二:直接用求根公式。

public class Solution {
    public int arrangeCoins(int n) {
        return (int)((-1.0 + Math.sqrt(1.0 + 8.0 * n)) / 2);
    }
}

方法三:二分法。

public class Solution {
    public int arrangeCoins(int n) {
        long i = 0, j = n;
        while (i <= j) {
            long m = (i + j) / 2;
            long sum = m * (1 + m) / 2;
            if (sum > n) j = m - 1; else i = m + 1;
        }
        return (int)j;
    }
}

方法四:累加

public class Solution {
    public int arrangeCoins(int n) {
        int i = 0;
        long sum = 0;
        while (sum + i + 1 <= n) {
            i++;
            sum += i;
        }
        return i;
    }
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章