难度: Easy
原题连接
内容描述
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.
思路 1 - 时间复杂度: O(lgN)- 空间复杂度: O(1)******
直接模拟,beats 48.90%
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
cnt = 1
while n > 0:
n -= cnt
cnt += 1
return cnt - 1 if n == 0 else cnt - 2
思路 2 - 时间复杂度: O(1)- 空间复杂度: O(1)******
可以直接公式:
i(i+1)/2 = n
解i
i = ( sqrt(8*n+1) -1 )/ 2
时间复杂度是O(1)是因为sqrt函数时间复杂度可以看成O(1),参考这里的讨论
beats 100%
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
return int((math.sqrt( 8 * n + 1) - 1 ) / 2)