Arrange coins
Problem description: You have a total of n coins, you need to arrange them in a ladder shape, and there must be exactly k coins in the kth row.
Given a number n, find the total number of rows that form a complete ladder row.
n is a non-negative integer and is in the range of a 32-bit signed integer.
For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/arranging-coins/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Exhaustive method
Simply accumulate until it is greater than n, and finally return the corresponding number of layers. This method is too inefficient and will time out when n is large.
Solution 2: Binary search method
First, the upper and lower limits low and high are the maximum and minimum layers respectively. The maximum value is estimated according to n = x * (x + 1) / 2
, and then use the binary search method to find the maximum number of layers that can be placed, and finally return the number of layers.
public class LeetCode_441 {
/**
* 穷举法,n超大时会超时,效率不高
*
* @param n
* @return
*/
public static int arrangeCoins(int n) {
int sum = 0, rows = 0;
for (int i = 1; ; i++) {
if (sum + i > n) {
break;
}
sum += i;
rows++;
}
return rows;
}
/**
* 二分查找法
*
* @param n
* @return
*/
public static int arrangeCoins2(int n) {
// low和high分别是最大和最小的层数,最大值根据 `n = x * (x + 1) / 2` 估算得到
int low = 1, high = (int) Math.sqrt(Double.valueOf(Integer.MAX_VALUE) * 2), mid = -1;
// 利用二分查找法找到最多可以放到第几层
while (low <= high) {
mid = (low + high) / 2;
double temp = (double) mid * (mid + 1) / 2;
if (temp > n) {
high = mid - 1;
} else if (temp < n) {
low = mid + 1;
} else {
return mid;
}
}
double temp = (double) mid * (mid + 1) / 2;
if (temp > n) {
return mid - 1;
} else {
return mid;
}
}
public static void main(String[] args) {
// 测试用例一,期望输出: 2
System.out.println(arrangeCoins2(5));
// 测试用例二,期望输出: 3
System.out.println(arrangeCoins2(8));
// 测试用例三,期望输出:65535
System.out.println(arrangeCoins2(2147483647));
// 测试用例三,期望输出:60070
System.out.println(arrangeCoins2(1804289383));
}
}
[Daily Message] If you wait for tomorrow to do everything, the opportunity will pass before your eyes.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。