【LeetCode】441. Arranging Coins

題目

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.

題解

這題剛開始用遞推,but超時了。
後來想了想,發現了數學方法:
m階所需要的coins爲m(m+1)/2;現有m個硬幣,我們可以假設x:
x(x+1) /2 = n;
解一元二次方程,對正根取整,得到能夠得到的stair number;
這裏很多人不理解爲啥向下取整就可以了。其實我們可以發現,假設正根x1向下取整爲k,則滿足:
k小於等於x1小於k+1;(不能打小於號,也是醉了)
那麼當coins爲k*(k+1)/2時的stair 數目是k,當coins爲(k+1)(k+2)/2時,stair 數目是k+1;
因此對於所有介於k*(k+1)/2與(k+1)(k+2)/2的所有n值,stair number =k;
那麼此時的k值就是能夠達到的stair number;

class Solution {
public:
    int arrangeCoins(int n) {
       return sqrt(2 * (long)n + 1 / 4.0) - 1 / 2.0;
    }
};

做完這題發現可以回初中重新讀書了(表情都發不出來);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章