[leetcode]441. Arranging Coins
Analysis
everyday is the first day of your rest life—— [间歇性迷茫+2~]
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.
简单来说就是1+2+3+…+k<=n && 1+2+3+…+(k+1)>=n,求满足条件的k.
Implement
方法一(二分搜索 O(lgN)):
class Solution {
public:
int arrangeCoins(int n) {
if(n <= 1)
return n;
long lo = 1;
long hi = n;
long mid;
while(lo<hi){
mid = lo+(hi-lo)/2;
if((1+mid)*mid/2 <= n)
lo = mid + 1;
else
hi = mid;
}
return lo-1;
}
};
方法二(暴力 O(N)):
class Solution {
public:
int arrangeCoins(int n) {
if(n <= 1)
return n;
int res = 0;
int tmp = 1;
while(n >= tmp){
res++;
n -= tmp;
tmp++;
}
return res;
}
};