441. Arranging Coins
You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.
Given the integer n, return the number of complete rows of the staircase you will build.
#Example 1:
Example 2:
Constraints:
1 <= n <= 231 - 1
不跑迴圈方式計算,直接找出row的關係(簡寫r)
1+2+3+…
可以透過梯形公式計算
整理過後
希望得到的結果是r = xxxx
透過(r+b)^2
跟n的關係, 再開根號
就可以知道算出r跟n的關係
國中數學的 (a+b)^2 公式, 觀察一下
其中,b是數字,公式後會產生額外的數字,再扣掉就好
先從2rb=r整理, 所以2b=1, 故b=1/2
會跟原本的函式多1/4(帶回原式時需扣掉)
調整原本函式
取得 r跟n的關係 r ≤ sqrt(2n + 1/4) - 1/2
利用Binary Search的方式夾出答案
根據題目可以得知,最少可能1層,最多不會超過n層
每次取中間抓層數,計算那層有多少
若太多把上限往中間拉,太少把下限往右邊拉
如果剛剛好表示剛好塞滿直接結束