在排序数组中查找元素的第一个和最后一个位置 二分法+递归

题目:

 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

 如果数组中不存在目标值 target,返回 [-1, -1]

思路:

 1 暴力遍历 从前往后  第一个  从后往前第一个

 2 二分法 + 递归

 


(一) 代码   二分法+递归

class Solution {
    int left =  Integer.MAX_VALUE;
    int right = Integer.MIN_VALUE;
    public int[] searchRange(int[] nums, int target) {
        if(nums.length == 0){
            return new int[]{-1,-1};
        }
        searchIndex(nums,target,0,nums.length - 1);
        if(left == Integer.MAX_VALUE){
            left = -1;
        }
        if(right == Integer.MIN_VALUE){
            right = -1;
        }
        return new int[]{left,right};
    }

    public void searchIndex(int[] nums,int target,int start,int end){
        //求mid
        int mid = (start + end) / 2;

        //递归出口
        if(start > end){
            return;
        }

        //找到目标数,更新  left and right
        if(nums[mid] == target){
            //若left 小于 mid
            if(left > mid){
                left = mid;
            }
            if(right < mid){
                right = mid;
            }
        }
        //左数组
        if(target <= nums[mid]){
            searchIndex(nums,target,start,mid- 1);
        }
        //右数组
        if(target >= nums[mid]){
            searchIndex(nums,target,mid + 1,end);
        }
    }
}

    反复在理解下,  就是背 

        

              背完在理解