441 Arranging Coins
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:
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.
2. Implementation
(1) Binary Search
思路:我们根据等差数列公式知道 coins的总数等于 row * (row + 1) / 2, 所以我们可以根据这个公式找出row的值,使得 row * (row + 1) / 2 小于等于n,即找row的右边界
class Solution {
public int arrangeCoins(int n) {
long start = 1, end = n, mid = 0;
long coins = (long)n;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (isGreaterThanN(mid, coins)) {
end = mid - 1;
}
else {
start = mid;
}
}
return isGreaterThanN(end, coins) ? (int)start : (int)end;
}
public boolean isGreaterThanN(long row, long coins) {
return (row * row + row) > 2 * coins;
}
}
3. Time & Space Complexity
Binary Search: 时间复杂度O(logn), 空间复杂度O(1)
Last updated
Was this helpful?