34. Search for a Range

来源:互联网 发布:厦门小牛网络 编辑:程序博客网 时间:2024/04/29 17:31

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};        return res;    }}

0 0