• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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.

count is the # of level, sum is the accumulated coins

 1 public class Solution {
 2     public int arrangeCoins(int n) {
 3         long sum = 0;
 4         int count = 0;
 5         while (true) {
 6             sum = sum + count;
 7             if (n < sum) break;
 8             count++;
 9         }
10         return count - 1;
11     }
12 }

 Better Solution:

Binary Search, 因为怕溢出,所以(1+m)m/2表示成了line6那种样子. 

 用m去估计最后返回的row

0.5*m+0.5*m*m > n 表示前m row的和大于了n, 如果这个m作为返回值的话肯定是取大了,所以r减小,如果
0.5*m+0.5*m*m <= n 表示m是合适的,或者偏小了,这个时候增大l,如果l>r,r就一定落在m处
 1 public class Solution {
 2     public int arrangeCoins(int n) {
 3         int l=1, r=n;
 4         while (l <= r) {
 5             int m = l + (r-l)/2;
 6             if (0.5*m+0.5*m*m > n) {
 7                 r = m - 1; 
 8             }
 9             else l = m + 1;
10         }
11         return r;
12     }
13 }

 

posted @ 2016-12-07 13:44  neverlandly  阅读(287)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3