34. Find First and Last Position of Element in Sorted Array (JAVA)

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given targetvalue.

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[] ret = new int[2];
        ret[0] = binaryLeftSearch(nums,target,0,nums.length-1);
        ret[1] = binaryRightSearch(nums,target,0,nums.length-1);
        return ret; 
    }
    
    public int binaryLeftSearch(int[] nums, int target, int left, int right){
        if(left > right) return -1;
        
        int mid = left + ((right-left)>>1);
        int mostLeft;
        if(target <= nums[mid]) {
            mostLeft = binaryLeftSearch(nums,target,left,mid-1);
            if(mostLeft == -1 && target==nums[mid]) mostLeft = mid;
        }
        else{ //target > nums[mid]
            mostLeft = binaryLeftSearch(nums,target,mid+1,right);
        }
        return mostLeft;
    }
    
    public int binaryRightSearch(int[] nums, int target, int left, int right){
        if(left > right) return -1;
        
        int mid = left + ((right-left)>>1);
        int mostRight;
        if(target >= nums[mid]) {
            mostRight = binaryRightSearch(nums,target,mid+1,right);
            if(mostRight == -1 && target==nums[mid]) mostRight = mid;
        }
        else{ //target < nums[mid]
            mostRight = binaryRightSearch(nums,target,left,mid-1);
        }
        return mostRight;
    }
}

猜你喜欢

转载自www.cnblogs.com/qionglouyuyu/p/10812178.html