Suppose we are given an array A[1 .. n] with the special property that A[1] ≥ A[2] and
A[n − 1] ≤ A[n]. We say that an element A[x] is a local minimum if it is less than or equal
to both its neighbors, or more formally, if A[x − 1] ≥ A[x] and A[x] ≤ A[x + 1]. For example,
there are five local minima in the following array:
9 7 7 2 1 3 7 5 4 7 3 3 4 8 6 9
We can obviously find a local minimum in O(n) time by scanning through the array. Describe
有些题目不难,主要是要深入分析
A[n − 1] ≤ A[n]. We say that an element A[x] is a local minimum if it is less than or equal
to both its neighbors, or more formally, if A[x − 1] ≥ A[x] and A[x] ≤ A[x + 1]. For example,
there are five local minima in the following array:
9 7 7 2 1 3 7 5 4 7 3 3 4 8 6 9
We can obviously find a local minimum in O(n) time by scanning through the array. Describe
and analyze an algorithm that finds a local minimum in O(log n) time
bool GetPivot(int a[], int n, int& res)
{
assert(a && n > 0);
int nBeg = 0;
int nEnd = n - 1;
while (nBeg + 2 <= nEnd)
{
int nMid = (nBeg + nEnd)/2;
if (a[nMid - 1] >= a[nMid] && a[nMid] <= a[nMid + 1])
{
res = a[nMid];
return false;
}
else if (a[nMid - 1] >= a[nMid] && a[nMid] > a[nMid + 1])
nBeg = nMid + 1;
else
nEnd = nMid - 1;
}
return false;
}
有些题目不难,主要是要深入分析