I recently encountered a problem during one of the Big 4's interview, the question is similar to the one below, and I believe there are many variations of this questions.
我最近在科技四大公司之一的面试中遇到了一个和下面列举的十分相似的问题,而在大厂的面试中,类似的变种问题数不胜数。
题干大致如下:
有K个鸡蛋,而你身在一个1到N层的建筑中。每个鸡蛋的功能都是相同的,打碎后就消失了。已知存在一个F层,F在0到N之间,如果在F层以上丢下鸡蛋,则鸡蛋会碎裂,反之则不会。每次你可以用一个鸡蛋在不同的楼层做自由落体,你的目标是找到F的值。用最小的实验次数完成测试。
For this question, it's a typical binary search scenario. Since 0 to F is safe, and F + 1 to N is the breakable floor, so it can abstract to a problem that finds some value in an ordered array. This is also solvable by using a linear search, but the problem is we have to use minimal moves to achieve that goal.
这个问题是个典型的二分查找问题,因为从0到F层是安全的,F+1到N层是可摔碎的,所以问题可以抽象成在已经排序的序列中查找特定的值。如果没有最少次数的限制,用线性查找或其他查找算法也是可以的。
The following code is a java version for this problem:
以下是java代码实现:
public int superEggDrop(int K, int N) {
return dp(K, N);
}
public int dp(int K, int N) {
int ans;
if (N == 0)
ans = 0;
else if (K == 1)
ans = N;
else {
int lo = 1, hi = N;
while (lo + 1 < hi) {
int x = (lo + hi) / 2;
int t1 = dp(K-1, x-1);
int t2 = dp(K, N-x);
if (t1 < t2)
lo = x;
else if (t1 > t2)
hi = x;
else
lo = hi = x;
}
ans = 1 + Math.min(Math.max(dp(K-1, lo-1), dp(K, N-lo)),
Math.max(dp(K-1, hi-1), dp(K, N-hi)));
}
return ans;
}
In conclusion, the linear search's time complexity is O(n) where the binary search is O(log 2 to the N).
对于线性查找,起算法时间复杂度为O(N),而二分查找则是O(log 2为底的对数).