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

##问题分析

该问题要求对已经排好的数组进行范围查找,邀请时间复杂度为O(log n)
为了满足该时间复杂度,应用二分查找的方法进行改造

##java代码
public class Solution {
public int[] searchRange(int[] A, int target) {
int low = 0;
int high = A.length - 1;
int[] flag = new int[2];
int flag_low,flag_high;
while(low <= high && low <= A.length - 1 && high <= A.length - 1){
int middle = low + ((high-low)>>1);
if(A[middle] == target){
flag_low = middle;
flag_high = middle;

                while(flag_low>=0 && A[flag_low] == target){
                    flag_low --;
                }
                while(flag_high<= A.length-1 && A[flag_high] == target){
                    flag_high ++;
                }
                flag[0] = flag_low + 1;
                flag[1] = flag_high - 1;
                return flag;
            } else if(A[middle] < target){
                low = middle + 1;
            } else{
                high = middle - 1;
            }
        }
        flag[0] = -1;
        flag[1] = -1;
        return flag;
    }
}

##注意

主要还是注意数组越界,还有二分的思想