Skip to content

Commit b1c2795

Browse files
committed
feat: add python and java solutions to leetcode problem: No.0441
1 parent fba5186 commit b1c2795

File tree

4 files changed

+27
-12
lines changed

4 files changed

+27
-12
lines changed

solution/0400-0499/0441.Arranging Coins/README.md

+14-2
Original file line numberDiff line numberDiff line change
@@ -42,22 +42,34 @@ n = 8
4242

4343
<!-- 这里可写通用的实现逻辑 -->
4444

45+
`(1 + x) * x / 2 <= n`,求解 x。
46+
47+
`(x + 1/2)² <= 2n + 1/4`,即 `x <= sqrt(2n + 1/4) - 1/2`
48+
49+
由于 2n 可能溢出,故转换为 `x <= sqrt(2) * sqrt(n + 1/8) - 1/2`
50+
4551
<!-- tabs:start -->
4652

4753
### **Python3**
4854

4955
<!-- 这里可写当前语言的特殊实现逻辑 -->
5056

5157
```python
52-
58+
class Solution:
59+
def arrangeCoins(self, n: int) -> int:
60+
return int(math.sqrt(2) * math.sqrt(n + 0.125) - 0.5)
5361
```
5462

5563
### **Java**
5664

5765
<!-- 这里可写当前语言的特殊实现逻辑 -->
5866

5967
```java
60-
68+
class Solution {
69+
public int arrangeCoins(int n) {
70+
return (int) (Math.sqrt(2) * Math.sqrt(n + 0.125) - 0.5);
71+
}
72+
}
6173
```
6274

6375
### **...**

solution/0400-0499/0441.Arranging Coins/README_EN.md

+8-2
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,19 @@ Because the 4th row is incomplete, we return 3.
6767
### **Python3**
6868

6969
```python
70-
70+
class Solution:
71+
def arrangeCoins(self, n: int) -> int:
72+
return int(math.sqrt(2) * math.sqrt(n + 0.125) - 0.5)
7173
```
7274

7375
### **Java**
7476

7577
```java
76-
78+
class Solution {
79+
public int arrangeCoins(int n) {
80+
return (int) (Math.sqrt(2) * Math.sqrt(n + 0.125) - 0.5);
81+
}
82+
}
7783
```
7884

7985
### **...**
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,5 @@
11
class Solution {
22
public int arrangeCoins(int n) {
3-
int l = 0, r = n;
4-
while (l < r) {
5-
int mid = l + r + 1 >>> 1;
6-
if (1L * mid * (mid + 1) / 2 <= n) l = mid;
7-
else r = mid - 1;
8-
}
9-
return r;
3+
return (int) (Math.sqrt(2) * Math.sqrt(n + 0.125) - 0.5);
104
}
11-
}
5+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
class Solution:
2+
def arrangeCoins(self, n: int) -> int:
3+
return int(math.sqrt(2) * math.sqrt(n + 0.125) - 0.5)

0 commit comments

Comments
 (0)