LeetCode 之二分法查找 Binary search

1. Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

首先二分,然后根据二分的坐标往左,往右

int searchTarget(int A[], int start, int end, int target){
    if(start > end)
        return -1;
    else{
        int mid = (start+end)/2;
        if(A[mid] == target) return mid;
        if(A[mid]> target)
            return searchTarget(A,start,mid-1,target);
        if(A[mid]<target)
            return searchTarget(A,mid+1,end,target);
    }
}
vector<int> searchRange(int A[], int n, int target) {
    vector<int> result;
    int index = searchTarget(A,0,n-1,target);
    if(index == -1){
        result.push_back(-1);
        result.push_back(-1);
        return result;
    }
    else{
        int ls = index;
        while(ls>0 && A[index] == A[ls-1]) ls--;
        int rs = index;
        while(rs<n-1 && A[index] == A[rs+1]) rs++;
        result.clear();
        result.push_back(ls);
        result.push_back(rs);
    }
    return result;

}

该算法的最差复杂度为O(n), 但平均为O(logn).


2. Pow(x,n)

Implement pow(xn).

二分法,注意n<0的情况。

double power(double x, int n){
    if(n==0)
        return 1;
    double v = power(x,n/2);
    if(n%2 == 0)
        return v *v;
    else
        return v* v* x;
}
double pow(double x, int n) {
    if(n<0)
        return 1.0 / power(x,-n);
    else
        return power(x,n);
}

3. 未完待续

你可能感兴趣的:(LeetCode,二分查找,binarySearch)