[leedcode 34] Search for a Range

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].

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        //本题是在已排序的数组中进行查找,因此应用二分查找的思想
        //牢记二分查找的参数以及函数!
        //当找到target数时,进行顺序查找,设置两个指针,一个是left,代表最侧不为target的下标。另一个是right,代表最右侧不为target的下标
        //注意int 数组的初始化!int a[]={-1,-1};
        int[] result={-1,-1};
        if(nums.length<1) return result;
        int res=find(nums,target,0,nums.length-1);
        if(res==-1){
            return result;
            
        }
        int left=res-1;
        int right=res+1;
        while(left>=0&&nums[left]==target){
                 left--;
        }
         while(right<nums.length&&nums[right]==target){
                 right++;
        }
        int rel[]={left+1,right-1};
        return rel;
    }
    public int find(int[] nums,int target,int start,int end){
        if(start>end) return -1;
        int mid=(start+end)/2;
        if(nums[mid]==target){
            return mid;
        }
        if(target>nums[mid]){
            return find(nums,target,mid+1,end);
        }else{
            return find(nums,target,start,mid-1);
        }
    }
}

 

你可能感兴趣的:(search)