题目:Given an array of integers sorted in ascending order, 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].
思路:利用双指针,前指针从头,后指针从尾开始向之间搜索。
public static int[] searchRange(int[] nums, int target) {
int[] result={-1,-1};
int starting=0;
int ending=nums.length-1;
while(starting<=ending)
{
if(nums[starting]==target)
{
result[0]=starting;
}
else{
starting++;
}
if(nums[ending]==target)
{
result[1]=ending;
}
else
{
ending--;
}
if(result[0]!=-1&&result[1]!=-1)
{
break;
}
}
return result;
}
Accepted后发现才击败12.7%Java提交。醉了。