34. Find First and Last Position of Element in Sorted Array(Medium)(二分变形好题)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NCUscienceZ/article/details/86991361

Given an array of integers nums 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].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

特判的时候容易错,二分变形好题

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int l = binarySearch(nums, target);
        if (l == nums.length || nums[l] != target){//特判错点
            return new int[]{-1, -1}; 
        }
        return new int[]{l, binarySearch(nums, target+1)-1}; 
    }
    
    public int binarySearch(int[] nums, int target){
        int l = 0, r = nums.length;
        while(l<r){
            int mid = l+((r-l) >> 1);
            if (nums[mid] < target){
                l = mid + 1;
            }else{
                r = mid;
            }
        }
        return l;
    }
     
}

猜你喜欢

转载自blog.csdn.net/NCUscienceZ/article/details/86991361