二分查找441

215 阅读1分钟

题目描述

你总共有 n 枚硬币,你需要将它们摆成一个阶梯形状,第 k 行就必须正好有 k 枚硬币。

给定一个数字 n,找出可形成完整阶梯行的总行数。

n 是一个非负整数,并且在32位有符号整型的范围内。

示例 1:

n = 5

硬币可排列成以下几行:
¤
¤ ¤
¤ ¤

因为第三行不完整,所以返回2.

示例 2:


n = 8

硬币可排列成以下几行:
¤
¤ ¤
¤ ¤ ¤
¤ ¤

因为第四行不完整,所以返回3.

解法(java版):

解题描述:

1、数学推导

2、for循环,如果在某一个数sum(i)>n>sum(i-1)

3、牛顿法

public class Title441 {

    //math
    /**
     * (n+1)*n/2=n
     * n*n + n =2n
     * n*n + n + 0.25=2n+0.25
     * (n+0.5)^2=2n+0.25
     * n=Math.sqrt(2n+0.25)-0.5
     **/

    public int arrangeCoins(int n) {
        return (int) (Math.sqrt(2*(long)n+0.25)-0.5);
    }
    
    public int arrangeCoinsNewton(int n) {
        double last=0;
        double res=1;
        double number=n;
        //如果精度大于10的10的-3次方,也就是0.01,则认为逼近y=0时x的值为多少
        while (Math.abs(last-res)>10e-3){
            last=res;
            res=(res*res+2*number)/(2*res+1);

        }
        int count = (int)res;
        int rest = count%2 == 0? n-(count/2)*(count+1): n-count*((count+1)/2);
        return rest <= count? count: count+1;
    }


    public static void main(String[] args) {
        //1e-15表示10的-15次方,你可以用输出语句输出验证一下!
        double err=1e-15;
        System.out.println(1e-15);
        System.out.println(new Title441().arrangeCoinsNewton(1804289383));
    }
}

gain:

1、此题用数学公式比较多,自己在纸上画一画,注意牛顿法