Find the interval binary search ---

Find the interval

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

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

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

Subject description:

  Count the number of times a number that appears in the sort array.

Analysis of ideas:

  This question is known by the title belongs to sort the array to find the problem, then we first thought is binary search. Due to the number of times to find a number that appears in the sort array, we just make sure the place and position of the last occurrence of the first occurrence of this number so we can calculate the number of times it appears in the array. Binary search algorithm to take the first intermediate digital and K array for comparison, if the number is greater than the middle of K, then we just need to find the next round of the first half period. If less than K, then we look in the latter half. If K is equal to that we have to determine this is not the first K K, before then we need to see if a number is K, if not then the middle number is the first K, if the previous number is K, then the first K certainly we look in the first half of the preceding paragraph, the next phase of the array. The same take to find the last K first intermediate array of digital and K for comparison, if the number is greater than the middle of K, then we just need to find the next round of the first half period. If less than K, then we look in the latter half. If equal K that we have to determine the K is not the last K, then we need to look after a number is not a K, if not then the number of intermediate and final K, if the number is K, then the last K certainly after the half, the next phase of the array we look in the latter half.

Code:

public int[]searchRange(int []nums,int target){
    if(nums==null||nums.length==0)
        return null;
    int first=0;
    int last=0;
    first=getFirst(nums,0,nums.length-1,target);
    last=getLast(nums,0,nums.length-1,target);
    if(first>-1&&last>-1){
        return new int[]{first,end};
    }
    return null;
}
public int getFirst(int []nums,int l,int h,int target){
    if(l>h)
        return -1;
    int mid=l+(h-l)/2;
    if(nums[mid]==target){
        if(mid>0&&nums[mid-1]!=target||mid==0){
            return mid
        }else{
            h=mid-1;
        }
    }else if(nums[mid]>target){
        h=mid-1;
    }else{
        l=mid+1;
    }   
     return getFirst(nums,l,h,target);
}
public int getLast(int []nums,int l,int h,int target){
    if(l>h)
        return -1;
    int mid=l+(h-l)/2;
    if(nums[mid]==target){
        if(mid<nums.length-1&&nums[mid+1]!=target||mid==nums.length-1){
            return mid;
        }else{
            l=mid+1;
        }
    }else if(nums[mid]>target){
        h=mid-1;
    }else{
        l=mid+1;
    }
    return getLast(nums,l,h,target);
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11106736.html