面试——手撕代码——二分查找——c++

二分查找

class Solution {
public:
    int search(vector<int>& nums, int target) {
        // write code here
        if(!nums.size()) return -1; 
        int l = 0,r = nums.size()-1;
        int mid;
        while(l<r){
            mid = (l+r)/2;
            if(nums[mid] == target) return mid;
            if(nums[mid]>target) {
                r = mid-1;
            }
            if(nums[mid]<target) {
                l = mid+1;
            }
        }
        if(nums[l] ==target ) return l;
        return -1;
    }
};

递归

int merge(vector<int> v, int n,int l,int r) {
	if (l > r) return -1;
	int mid = (l + r) / 2;
	if (v[mid] == n) return mid;
	if (v[mid] < n) return merge(v, n, mid + 1, r);
	if (v[mid] > n) return merge(v, n,l, mid-1);
}