leetcode 34 Search for a Range

题目详情

Given an array of integers sorted in ascending order, 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].

题目的意思是,输入一个升序排列的整数数组和一个目标值。咱们要找出这个目标数字在数组中的存在区间,并以数组形式返回这个区间。若是这个数字不存在于数组之中,则返回{-1.-1}。要求题目必须在O(logn)数组

For example,
输入数组[5, 7, 7, 8, 8, 10]和目标值8,
返回[3, 4].指针

想法

  • 咱们须要分别找出最左边的这个元素的位置、和最右边的这个元素的位置。
  • 因为对于时间的要求,咱们在进行查找的时候要采起二分查找。
  • 须要注意的是,对于寻找左边界的时候,若是nums[i]等于target值,也要将mid赋值为高位指针high,以找到最左边的等于target的元素。

解法

public int[] searchRange(int[] nums, int target) {
        int[] res = {-1,-1};
        int leftIndex = findIndex(nums,target,true);
        if(leftIndex == nums.length || nums[leftIndex] != target){
            return res;
        }
        
        res[0] = leftIndex;
        res[1] = findIndex(nums,target,false)-1;
        
        return res;
    }
    public int findIndex(int[] nums,int target,boolean left){
        int low = 0;
        int high = nums.length;
        
        while(low < high){
            int mid = (low + high)/2;
            if(nums[mid] > target ||(left && target == nums[mid])){
                high = mid;
            }else{
                low = mid +1;
            }
        }       
        return low;
    }
相关文章
相关标签/搜索