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; }
2. Pow(x,n)
Implement pow(x, n).
二分法,注意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); }