您的位置:首页 > 其它

34. Search for a Range

2016-03-21 11:22 429 查看
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]
.

Subscribe to see which companies asked this question
先找前面的 再找后面的 没难度

public class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums.length==1&&nums[0]==target){
int [] re ={0,0};
return re;
}
if(nums.length==1&&nums[0]!=target){
int [] re ={-1,-1};
return re;
}
int a = 0;
int c = nums.length-1;
int b = (a+c)/2;
int first = -1;
int last = -1;
while(c-a>=10){//先找前面的
if(nums[b]>=target){//前面的落在前半截
c=b;
b=(a+c)/2;
continue;
}else{
a=b;
b=(a+c)/2;
continue;
}
}
if(nums[0]==target){first=0;}else{
for(int i=a;i<=c;i++){
if(nums[i]==target&&nums[i-1]<target){first=i;break;}
}
}
a=0;c=nums.length-1;b=(a+c)/2;
while(c-a>=10){//再找后面的
if(nums[b]<=target){//
a=b;
b=(a+c)/2;
continue;
}else{
c=b;
b=(a+c)/2;
continue;
}
}
if(nums[nums.length-1]==target){last=nums.length-1;}else{
for(int i=c;i>=a;i--){
if(nums[i]==target&&nums[i+1]>target){last=i;break;}
}}
int [] res = {first,last};

4000
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: