您的位置:首页 > 其它

Search for a Range

2015-07-22 10:37 399 查看
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].

题目要求了时间复杂度,因此需要用二分搜索。

在num[i]==target时处理完毕应该返回arr,否则会死循环。写代码为这个问题纠结很久。

public class Solution {
public int[] searchRange(int[] nums, int target) {
int[] arr={-1,-1};
int left=0,right=nums.length-1;
if(right<left)
return arr;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]==target){
while(nums[left]<target)left++;
while(nums[right]>target)right--;
arr[0]=left;arr[1]=right;
return arr;
}
else if(nums[mid]<target)
left=mid+1;
else
right=mid-1;
}
return arr;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: