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.(给你n枚硬币来组成一个阶梯形,这个阶梯每第k行必须包含k枚硬币)
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.
1.个人分析
从例子中观察分析可以看得出其中的求解规律,将输入的n不断进行减1,2,3…,直到n<=0为止。
2.个人解法
int arrangeCoins(int n)
{
int i;
for (i=1; n>0; ++i){
n -= i;
}
if(n < 0)
return i - 2;
else
return i - 1;
}
3.参考解法
(1)
int arrangeCoins(int n)
{
if(n <= 1) return n;
long left = 0, right = n;
while(left <= right){
long mid = left + (right - left)/2;
long sum = ((1 + mid) * mid)/2;
if(sum <= n){
left = mid + 1;
}else {
right = mid - 1;
}
}
return left - 1;
}
(2)
int arrangeCoins(int n)
{
return sqrt(2 * (long)n + 1 / 4.0) - 1 / 2.0;
}
4.总结
第一种解法是最简单直接的方法,时间复杂度为O(n)(也有说是O(sqrt(n)));第二种则采用了二分查找的思路,时间复杂度为O(logn);第三种则是利用一元二次方程求根的数学方法求解,时间复杂度为O(1),但不明白为什么该问题与一元二次方程求根等价。
PS:
- 题目的中文翻译是本人所作,如有偏差敬请指正。
- 其中的“个人分析”和“个人解法”均是本人最初的想法和做法,不一定是对的,只是作为一个对照和记录。