[LeetCode] 441. Arranging Coins 排列硬币

Posted 轻风舞动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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.

 C++: Time: O(n), Space: O(1)

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;
    }
};

C++: Time: O(logn), Space: O(1)

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;
    }
};

C++: Time: O(logn), Space: 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); # sqrt is O(logn) time.
} };

Python: O(logn), Space: O(1)

class Solution2(object):
    def arrangeCoins(self, n):
        """
        :type n: int
        :rtype: int
        """
        left, right = 1, n
        while left <= right:
            mid = left + (right - left) / 2
            if 2 * n < mid * (mid+1):
                right = mid - 1
            else:
                left = mid + 1
        return left - 1

Python: O(logn), Space: O(1)

class Solution(object):
    def arrangeCoins(self, n):
        """
        :type n: int
        :rtype: int
        """
        return int((math.sqrt(8*n+1)-1) / 2)  # sqrt is O(logn) time.

  

  

  

  

  

 

以上是关于[LeetCode] 441. Arranging Coins 排列硬币的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 441. Arranging Coins

LeetCode 441. Arranging Coins

LeetCode 441 Arranging Coins

Leetcode441--数学Arranging Coins

leetcode练习:441. Arranging Coins

[Leetcode + Lintcode] 441. Arranging Coins