# 441. Arranging Coins

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/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.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(lgN)******- 空间复杂度: O(1)******

直接模拟，beats 48.90%

```python
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)，参考这里的[讨论](https://cs.stackexchange.com/questions/63181/big-o-complexity-of-sqrtn)

beats 100%

```python
class Solution(object):
    def arrangeCoins(self, n):
        """
        :type n: int
        :rtype: int
        """
        return int((math.sqrt( 8 * n + 1) - 1 ) / 2)
```
