题目:
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]
.
从题目中获取到关键字:sorted array ,find...position, a given target value, O(logn).
这些关键字都在提醒我们这道题的思路应该是二分查找法。
二分查找方法
二分查找经常用来在有序的数列查找某个特定的位置。
因此,应用二分查找法,这个数列必须包含以下特征:
- pos = mid;
high = mid - 1;
low = mid + 1;
res[0] = pos;
res[1] = pos;
}
}
newlow = newmid + 1;
newhigh = newmid - 1;
}
res[1] = newhigh;
newhigh = pos;
newhigh = newmid - 1;
newlow = newmid + 1;
}
res[0] = newlow;
}