[LeetCode] 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.

 

這道題給了我們n個硬幣,讓我們按一定規律排列,第一行放1個,第二行放2個,以此類推,問我們有多少行能放滿。通過分析題目中的例子可以得知最后一行只有兩種情況,放滿和沒放滿。由於是按等差數列排放的,我們可以快速計算出前i行的硬幣總數。我們先來看一種O(n)的方法,非常簡單粗暴,就是從第一行開始,一行一行的從n中減去,如果此時剩余的硬幣沒法滿足下一行需要的硬幣數了,我們之間返回當前行數即可,參見代碼如下:

 

解法一:

class Solution {
public:
    int arrangeCoins(int n) {
        int cur = 1, rem = n - 1;
        while (rem >= cur + 1) {
            ++cur;
            rem -= cur;
        }
        return n == 0 ? 0 : cur;
    }
};

 

再來看一種O(lgn)的方法,用到了二分搜索法,我們搜索前i行之和剛好大於n的臨界點,這樣我們減一個就是能排滿的行數,注意我們計算前i行之和有可能會整型溢出,所以我們需要將變量都定義成長整型,參見代碼如下:

 

解法二:

class Solution {
public:
    int arrangeCoins(int n) {
        if (n <= 1) return n;
        long low = 1, high = n;
        while (low < high) {
            long mid = low + (high - low) / 2;
            if (mid * (mid + 1) / 2 <= n) low = mid + 1;
            else high = mid;
        }
        return low - 1;
    }
};

 

再來看一種數學解法O(1),充分利用了等差數列的性質,我們建立等式, n = (1 + x) * x / 2, 我們用一元二次方程的求根公式可以得到 x = (-1 + sqrt(8 * n + 1)) / 2, 然后取整后就是能填滿的行數,一行搞定簡直喪心病狂啊:

 

解法三:

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

 

參考資料:

https://discuss.leetcode.com/topic/65664/my-55ms-c-solution

https://discuss.leetcode.com/topic/65575/java-o-1-solution-math-problem

https://discuss.leetcode.com/topic/65631/c-three-solutions-o-n-o-logn-o-1/2

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM