问题:
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
我们要找到满足以下条件的x:
1 + 2 + 3 + 4 + 5 + 6 + 7 + ... + x <= n
即sum_{i=1}^x i <= n (i从1到x求和)
对它进行简化求和可以得到(x * ( x + 1)) / 2 <= n
在这种情况下,使用折半查找来慢慢缩小满足方程的x的范围。
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
即sum_{i=1}^x i <= n
求和可得(x * ( x + 1)) / 2 <= n
利用一元二次方程求根公式可得:
x = 1 / 2 * (-sqrt(8 * n + 1)-1)(为负数,不符合题意)
或 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型数据
}
}