1. 程式人生 > >34. Find First and Last Position of Element in Sorted Array

34. Find First and Last Position of Element in Sorted Array

題意:

一個有序陣列中有重複元素,返回第一個和最後一個target的下標。要求O(logN)。

思路:

沒什麼好說的,還是二分法。

vector<int> searchRange(vector<int>& nums, int target) {
	int l = 0, r = nums.size() - 1, mid, sz = nums.size(), get = -1;
	if (sz == 0)
		return{ -1,-1 };
	while (l <= r) {
		mid = (l + r) / 2;
		if (nums[mid] == target) {
			get = mid;
			break;
		}
		else if (nums[mid] > target)
			r = mid - 1;
		else
			l = mid + 1;
	}
	if (get == -1)
		return{ -1,-1 };
	int first = get, last = get;
	while (first >= 1 && nums[first - 1] == nums[first])
		--first;
	while (last <= sz - 2 && nums[last + 1] == nums[last])
		++last;
	return{ first,last };
}