Skip to content

Commit a1a9982

Browse files
committed
modify code
1 parent 752eae9 commit a1a9982

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

src/class42/Code02_ThrowChessPiecesProblem.java

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
// 方法1和方法2会超时
55
// 方法3勉强通过
66
// 方法4打败100%
7+
// 方法5打败100%,方法5是在方法4的基础上做了进一步的常数优化
78
public class Code02_ThrowChessPiecesProblem {
89

910
public static int superEggDrop1(int kChess, int nLevel) {
@@ -91,6 +92,26 @@ public static int superEggDrop3(int kChess, int nLevel) {
9192
}
9293

9394
public static int superEggDrop4(int kChess, int nLevel) {
95+
if (nLevel < 1 || kChess < 1) {
96+
return 0;
97+
}
98+
int[] dp = new int[kChess];
99+
int res = 0;
100+
while (true) {
101+
res++;
102+
int previous = 0;
103+
for (int i = 0; i < dp.length; i++) {
104+
int tmp = dp[i];
105+
dp[i] = dp[i] + previous + 1;
106+
previous = tmp;
107+
if (dp[i] >= nLevel) {
108+
return res;
109+
}
110+
}
111+
}
112+
}
113+
114+
public static int superEggDrop5(int kChess, int nLevel) {
94115
if (nLevel < 1 || kChess < 1) {
95116
return 0;
96117
}
@@ -134,7 +155,8 @@ public static void main(String[] args) {
134155
int ans2 = superEggDrop2(K, N);
135156
int ans3 = superEggDrop3(K, N);
136157
int ans4 = superEggDrop4(K, N);
137-
if (ans2 != ans3 || ans2 != ans4) {
158+
int ans5 = superEggDrop5(K, N);
159+
if (ans2 != ans3 || ans4 != ans5 || ans2 != ans4) {
138160
System.out.println("出错了!");
139161
}
140162
}

0 commit comments

Comments
 (0)