美文网首页
2022-04-25 「278. 第一个错误的版本」

2022-04-25 「278. 第一个错误的版本」

作者: 柠香萌萌鸡 | 来源:发表于2022-04-25 09:17 被阅读0次

今日简单题:https://leetcode-cn.com/problems/first-bad-version/

比较清晰的二分法,关注下while不要死循环即可。
另外吐槽一下题解,mid=head+(tail-head)/2; 那不就是mid=(head+tail)/2吗?这个还更直观,就是中位数。

贴下代码:

/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int head = 1;
        int tail = n;
        int tmp = (head+tail)/2;
        while(head < tail) {  
            // 如果tmp是坏版本,那第一个坏版本一定在它左边
            if (isBadVersion(tmp)) {
                tail = tmp;
            }
            else {
                head = tmp + 1;
            }
            tmp = (head+tail)/2;
        }
        return head;
    }
}

相关文章

网友评论

      本文标题:2022-04-25 「278. 第一个错误的版本」

      本文链接:https://www.haomeiwen.com/subject/ddhfyrtx.html