0%

arranging-coins

Arranging Coins – LeetCode 441

Problem

Description

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

n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.

Answer

Original

Code

1
2
3
4
5
6
class Solution {
public:
int arrangeCoins(int n) {
return (sqrt(1 + 8 * static_cast<unsigned long>(n)) - 1) / 2;
}
};

思路

数学题,一元二次方程。时间复杂度$O(1)$,空间复杂度$O(1)$。
耗时$3$ ms,排名$20.39\%$

Better

思路

还没看到更好的思路。