[Leetcode] First Bad Version

Source: Internet
Author: User
Tags versions
Topics

https://leetcode.com/problems/first-bad-version/

You is a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since Each version was developed based on the previous version and all of the versions after a bad version were also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones T O is bad.

Given an API bool Isbadversion (version) which would return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Code

21/21 Test Cases passed
runtime:0 ms

The main need to note is that N may be large, low+high and mid+1 may be more than int, so use long.

Forward Declaration of isbadversion API.
BOOL Isbadversion (int version);

int firstbadversion (int n) {
    if (n = = 1) {
        return 1;
    }
    Long low = 1;
    Long high = n;
    Long mid = 0;
    while (low <= high) {
        mid = (low + high)/2;//may exceed int, so use long
        bool bad = Isbadversion (mid);
        if (bad) {High
            = mid-1,
        } else {Low
            = mid + 1;
        }
    }

    return high + 1;
}
attached: some inputs
Last executed input:2147483647 versions 2147483647 was the first bad
version.
Last executed input:2126753390 versions 1702766719 was the first bad
version.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.