441 Arranging Coins

1. Question

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.
nis a non-negative integer and fits within the range of a 32-bit signed integer.
Example 1:
1
n = 5
2
3
The coins can form the following rows:
4
¤
5
¤ ¤
6
¤ ¤
7
8
Because the 3rd row is incomplete, we return 2.
Copied!
Example 2:
1
n = 8
2
3
The coins can form the following rows:
4
¤
5
¤ ¤
6
¤ ¤ ¤
7
¤ ¤
8
9
Because the 4th row is incomplete, we return 3.
Copied!

2. Implementation

(1) Binary Search
思路:我们根据等差数列公式知道 coins的总数等于 row * (row + 1) / 2, 所以我们可以根据这个公式找出row的值,使得 row * (row + 1) / 2 小于等于n,即找row的右边界
1
class Solution {
2
public int arrangeCoins(int n) {
3
long start = 1, end = n, mid = 0;
4
long coins = (long)n;
5
6
while (start + 1 < end) {
7
mid = start + (end - start) / 2;
8
9
if (isGreaterThanN(mid, coins)) {
10
end = mid - 1;
11
}
12
else {
13
start = mid;
14
}
15
}
16
return isGreaterThanN(end, coins) ? (int)start : (int)end;
17
}
18
19
public boolean isGreaterThanN(long row, long coins) {
20
return (row * row + row) > 2 * coins;
21
}
22
}
Copied!

3. Time & Space Complexity

Binary Search: 时间复杂度O(logn), 空间复杂度O(1)