码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 441. Arranging Coins 排列硬币

时间:2018-02-28 14:04:40      阅读:354      评论:0      收藏:0      [点我收藏+]

标签:while   fit   ++   ret   def   pytho   AC   must   ber   

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 排列硬币

标签:while   fit   ++   ret   def   pytho   AC   must   ber   

原文地址:https://www.cnblogs.com/lightwindy/p/8483034.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!