バイナリサーチLintcodeNo14

ターゲットの位置14First

基本的な質問のバイナリ検索

STLは達成LOWER_BOUND

class Solution {
public:
    /**
     * @param nums: The integer array.
     * @param target: Target to find.
     * @return: The first position of target. Position starts from 0.
     */
    int binarySearch(vector<int> &nums, int target) {
        // write your code here
        
        auto res_it=lower_bound(nums.begin(),nums.end(),target);
        auto it=nums.begin();
        int i=0;
        if(*res_it != target)return -1;
        return &(*res_it)-&(nums[0]);
        
    }
};

イテレータと添字は、アドレス変換シンボルのために使用することができる(ベクター原理をメモリに連続的に可変分散されます)

伝統的なアルゴリズム

class Solution {
public:
    /**
     * @param nums: The integer array.
     * @param target: Target to find.
     * @return: The first position of target. Position starts from 0.
     */
    int binarySearch(vector<int> &nums, int target) {
        // write your code here
        
        int left = -1;
        int right = nums.size();
        
        while(right - left > 1)
        {
            int mid = (left+right)/2;
            if(target<=nums[mid])
            {
                right = mid;
            }else{
                left = mid;
            }
            
        }
        if(nums[right] != target)return -1;
        return right;

    }
};

なお、

  • 左開区間(理由は、整数変数である= 3(2 + 3)/ 2)
  • 中間体(右= MID)の右側をプルするときに検索数=とき

おすすめ

転載: www.cnblogs.com/virgildevil/p/11824267.html