Leetcode 441. Arranging Coins

来源:互联网 发布:ubuntu 优麒麟 编辑:程序博客网 时间:2024/05/17 06:36

Math. Solve the quadratic function k/2(k+1) <= n.

k <= (-1+(1+8n)^1/2) / 2.

public class Solution {    public int arrangeCoins(int n) {        // math        return (int) (-1+Math.sqrt(1+8*(double)n))/2;    }}
Binary search.

public class Solution {    public int arrangeCoins(int n) {        // set k's higher bound as n        int low = 1, high = n, mid = 0;        while (low + 1 < high) {            mid = low + (high - low) / 2;            if (0.5*mid + 0.5*mid*mid <= n)                low = mid;            else                high = mid;        }        if (0.5*low+0.5*low*low <= n) return low;        return high;    }}


0 0