leetcode_441. Arranging Coins 分配硬币构造台阶

来源:互联网 发布:redis 数据库大小 编辑:程序博客网 时间:2024/06/05 09:18

题目:

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 = 5The coins can form the following rows:¤¤ ¤¤ ¤Because the 3rd row is incomplete, we return 2.

Example 2:

n = 8The coins can form the following rows:¤¤ ¤¤ ¤ ¤¤ ¤Because the 4th row is incomplete, we return 3.

题意:

给定n个硬币,第i级台阶需要i个硬币,问n个硬币最多可构成几级台阶?


代码:

class Solution(object):
    import math
    
    def arrangeCoins(self, n):
        """
        :type n: int
        :rtype: int
        """
        


        if n <= 0 :
            return 0
        else :
            res = 1
            i = 1
            while res < n :
                i += 1
                res += i
            if res == n :
                return i
            else :
                return i-1


笔记:

本代码的思路是等差数列求和公式,从i=1开始迭代,推出n个硬币可构成的台阶数。当然,效率太低,但还是AC了。

网上通用效率高的算法是,直接根据n解出台阶数k,也是从等差数列求和公式出发,推导出k的表达式:

/* 数学推导 
假设完成K层,一共N个,由等差数列求和公式有: 
(1+k)*k/2 = n 
一步步推导: 
k+k*k = 2*n 
k*k + k + 0.25 = 2*n + 0.25 
(k + 0.5) ^ 2 = 2*n +0.25 
k + 0.5 = sqrt(2*n + 0.25) 
k = sqrt(2*n + 0.25) - 0.5 
这里k是个浮点数,将其取为小于k的最大整数就可以 
*/

 参考:http://blog.csdn.net/mebiuw/article/details/52981579



0 0
原创粉丝点击