class Solution {
public:
int arrangeCoins(int n) {
if(n==1) return 1;
int l=1,r=n;
while(l<=r){
int mid=l+(r-l)/2;
if((long long)2*n>=(long long)(mid+1)*mid){
l=mid+1;
}
else{
r=mid-1;
}
}
return l-1;
}
};
暴力模拟:
class Solution {
public:
int arrangeCoins(int n) {
long now = 0; // 当前层
long count = 0; // 加上 level 层之后,总的有多少硬币
while (count + now + 1 <= n) { // level + 1 表示下一层的数目
now ++; // 得到下一层的数目
count += now; // 累加下一层的数目
}
return now;
}
};
https://ojeveryday.github.io/AlgoWiki/#/BinarySearch/README



