# 分配硬币 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.```

① 按照第i行会有i个硬币分配，当n<0时，停止计数即可。55ms

public class Solution {
public int arrangeCoins(int n) {
int i = 1;
int count = 0;
while(n > 0){
n = n - i;
i ++;
if(n >= 0){
count ++;
}
}
return count;
}
}
② 采用折半查找的方式：46ms

1 + 2 + 3 + 4 + 5 + 6 + 7 + ... + x <= n

public class Solution {
public int arrangeCoins(int n) {
int start = 0;
int end = n;
while (start <= end){
int mid = (end - start) / 2 + start; //(end - start) / 2 + start  VS  (start + end) >>> 1
if ((0.5 * mid * mid + 0.5 * mid ) <= n){//公式
start = mid + 1;
}else{
end = mid - 1;
}

}
return start - 1;
}
}

③ 利用一元二次方程求根的数学方法求解：47ms

1 + 2 + 3 + 4 + 5 + 6 + 7 + ... + x <= n

x = 1 / 2 * (-sqrt(8 * n + 1)-1)（为负数，不符合题意）

public class Solution {
public int arrangeCoins(int n) {//(int)((sqrt(1 + 8 * (long)n)-1) / 2)
return (int) ((Math.sqrt(1 + 8.0 * n) - 1) / 2);// java会将中间结果自动装箱为long型数据
}
}

### 叶枫啦啦

2017/12/24
0
0
LeetCode 322. Coin Change （硬币找零）

dby_freedom
12/06
0
0

YinTokey
05/27
0
0

2016/11/22
2
0

SVD
2016/09/13
112
0

Dubbo下一站：Apache顶级项目

13分钟前
1
0
Vim中快捷键命令介绍

map命令简介 map是一个映射命令,将常用的很长的命令映射到一个新的功能键上。map是Vim强大的一个重要原因，可以自定义各种快捷键，用起来自然得心应手。Vim中有五种映射存在： 用于普通模式:...

17分钟前
2
0

19分钟前
1
0
Docker | 采用镜像alpine缺少时区解决方法

20分钟前
2
0

31分钟前
3
0