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].
class Solution {public:vector<int> searchRange(vector<int>& nums, int target) {int temp[] = { -1, -1 };vector<int> ret(temp, temp + 2);if (nums.size() == 0)return ret;int l = 0;int r = nums.size();int mid = 0;while (l <= r){mid = (l + r) / 2;if (nums[mid] == target)break;else if (nums[mid]>target)r = mid - 1;elsel = mid + 1;}if (nums[mid] != target){return ret;}l = r = mid;while (nums[l] == target&&l>0)l--;while (r<nums.size() && nums[r] == target)r++;if (nums[l] != target)l++;if (r>=nums.size()||nums[r] != target)//注意r可能为nums.size(),这种情况也要r--r--;ret[0] = l;ret[1] = r;return ret;}};
原文:http://www.cnblogs.com/zhoudayang/p/5039456.html