首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode441. Arranging Coins

leetcode441. Arranging Coins

作者头像
眯眯眼的猫头鹰
发布2019-07-02 14:24:21
2430
发布2019-07-02 14:24:21
举报

题目要求

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个硬币搭台阶,要求第k级台阶必须有k个硬币。问n个硬币最多能够搭多少级台阶? 如五个硬币最多能够搭两级台阶,8个硬币最多搭三级台阶。

思路和代码

反过来讲,如果要搭k级台阶,那么k级台阶共包含(k+1) * k / 2个硬币。因此我们只需要找到可以搭建的台阶的边界,并采用二分法将边界不断缩小直到达到最大的台阶数。

    public int arrangeCoins(int n) {
        long rgt = (int) (Math.sqrt(n) * Math.sqrt(2) + 1);
        long lft = 0;
        while(lft <= rgt) {
            long mid = lft + (rgt -lft) / 2;
            long total = (mid + 1) * mid / 2;
            if(total <= n) {
                lft = mid + 1;
            }else {
                rgt = mid - 1;
            }
        }
        return (int)lft-1;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档