leetcode-Sqrt(x)與Bad version

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;
    }





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章