leetcode-Sqrt(x)与Bad version

来源:互联网 发布:单片机可靠性 编辑:程序博客网 时间:2024/06/06 10:49
Sqrt(x) vs First bad version
1. Sqrt(x)
题目:Implement int sqrt(int x).
思路:看到这道题目首先注意到返回的值都是整型变量。那么当x小于第一个i^2(i>=2)的时候,sqrt(x)的值都是i-1,于是题目就转换成为求第一个x/i^2==0的i的问题。我们可以用暴力搜索,直接遍历i,但是这样会造成TEL。所以我们可以使用二分法搜索。
类比:这道题目和求Bad version的题目很像。参考2.
注意点:
(1) 注意二分搜索中的整型下标的范围,不要越界
(2) 注意x/i^2的写法,写成i^2有可能会越界,所以可以写成x/i/i

      int mySqrt(int x) {        if (x <= 0)        {            return 0;        }        if ( x == 1)        {            return 1;        }        int low = 1, high = x, mid;        mid = low + (high - low) / 2; //防止下标越界        while ( low < high )        {            if ( x / mid / mid  ) //防止i^2越界            {                low = mid + 1;            }            else            {                high = mid;            }            mid = low + (high - low) / 2;        }        return mid-1;      }

2. First bad version
题目:
You are 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 is developed based on the previous version, all the versions after a bad version are 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 to be bad. You are given an API bool isBadVersion(version) which will return whether version is bad.
int firstBadVersion(int n) {        int p = 1, r = n;        int mid = p+(r-p)/2;        while ( p<r ){            if ( isBadVersion(mid) )            {                r = mid;            } //is Bad             else{                p = mid+1;            } //is good             mid = p+(r-p)/2;        }        return mid;    }




0 0