1. 程式人生 > >【二分查詢】Search for a Range

【二分查詢】Search for a Range

Given a sorted array of integers, 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].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4]

.

解法:特殊的二分,在找到首個val後要進行判斷它的前面是否還有符合的值;同理找最後一個
public class Solution {
    public int searchFirst(int []num, int val){
        int low = 0;
        int high = num.length-1;
        while(low <= high){
            int mid = (low + high) / 2;
            if(num[mid] == val){
                if(mid-1 >= 0 && num[mid-1] == val ) high = mid-1;
                else return mid;
            }
            else if(num[mid] > val) high = mid - 1;
            else low = mid + 1;
        }
        return -1;
    }
    
    public int searchLast(int [] num, int val){
        int low = 0;
        int high = num.length-1;
        while(low <= high){
            int mid = (low + high) / 2;
            if(num[mid] == val){
                if(mid+1 < num.length && num[mid+1] == val ) low = mid+1;
                else return mid;
            }
            else if(num[mid] > val) high = mid - 1;
            else low = mid + 1;
        }
        return -1;
    }
    
    public int[] searchRange(int[] A, int target) {
        int first = searchFirst(A, target);
        int last = searchLast(A, target);
        int b[] = new int[2];
        b[0] = first;
        b[1] = last;
        return b;
    }
}