binary search

binary search

  • low = 0 , high = n - 1;
    偶数个 [low,mid] | [mid + 1, high]
    奇数个 left) mid (right

  • low = 0 , high = n;
    偶数个 [low,mid - 1] | [mid, high) = [low,mid) | [mid,high)[左闭右开区间]
    奇数个 [low,mid) | [mid,high) 右边更多一些。

leetcode35. Search Insert Position

leetcode35

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int low = 0,high = nums.size() - 1;
        
        while(low <= high)
        {
            int mid = (low + high)>>1;
            
            if(nums[mid] < target)
                low = mid + 1;
            else 
                high = mid - 1;
        }
        return low;
    }
};

leetcode33. Search in Rotated Sorted Array

leetcode33

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int lo = 0, hi = nums.size() - 1;
        int mid;
        while(lo <= hi)
        {
            mid = (lo + hi) >> 1;
            if(nums[mid] == target) return mid;
            
            if(nums[mid] >= nums[lo])
            {
                if(target >= nums[lo] && target < nums[mid])
                {
                    hi = mid - 1;
                }
                else
                {
                    lo = mid + 1;
                }
            }
            else
            {
                if(target > nums[mid] && target <= nums[hi])
                {
                    lo = mid + 1;
                }
                else
                {
                    hi = mid - 1;
                }
            }
        }
        return -1;
    }
};

leetcode81. Search in Rotated Sorted Array II

leetcode81

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int hi = nums.size() - 1;
        return bin(nums,target,0,hi);
    }
    
    bool bin(vector<int>& nums, int target, int lo, int hi)
    {
        if(lo > hi) return false;
        int mid = (lo + hi) >> 1;
        if(target == nums[mid]) return true;
        bool left,right;
        left = right = false;
        if(nums[mid] >= nums[lo])
        {
            if(nums[lo] <= target && nums[mid] > target)
            {
                left = bin(nums,target,lo,mid - 1);
            }
            else
            {
                left = bin(nums,target,mid + 1,hi);
            }
        }
        
        if(nums[mid] <= nums[hi])
        {
            if(nums[mid] < target && target <= nums[hi])
            {
                right = bin(nums,target,mid + 1,hi);
            }
            else
            {
                right = bin(nums,target,lo,mid - 1);
            }
        }
        
        return left || right;
    }
};

posted on 2017-07-25 11:04  炮二平五  阅读(197)  评论(0编辑  收藏  举报

导航