21.03.14 LeetCode34. 在排序数组中查找元素的第一个和最后一个位置

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

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

进阶:

你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
 

示例 1:

输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例 2:

输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例 3:

输入:nums = [], target = 0
输出:[-1,-1]

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int len = nums.length;
        if(len==0)
            return new int[]{-1,-1};
        int firstIndex = findFirstIndex(nums,target);
        if(firstIndex == -1)
            return new int[]{-1,-1};
        int lastIndex = findLastIndex(nums, target);
        return new int[] { firstIndex,lastIndex};
    }
    public int findFirstIndex(int[] nums,int target)
    {
        //典型二分
        int left = 0,right = nums.length-1;
        while(left<right)
        {
            int mid = left + (right-left)/2;
            if(nums[mid] > target)
                right = mid-1;
            else if(nums[mid] == target)
                right = mid;
            else
                left = mid+1;
        }
        if(nums[left] == target)
            return left;
        return -1;
    }
    public int findLastIndex(int[] nums,int target)
    {
        int left = 0,right = nums.length-1;
        while(left<right)
        {
            //这里注意计算mid位置时有+1行为,属于mid向上取整,否则下面left=mid会死循环
            int mid = left + (right-left +1)/2;
            if(nums[mid] > target)
                right = mid-1;
            else if(nums[mid] == target)
                left = mid;
            else
                left = mid+1;
        }
        return left;
    }
}

 

posted @ 2021-03-14 00:13  γGama  阅读(50)  评论(0编辑  收藏  举报