LeetCode Solutions : 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]

Java Solutions:

1.because of O(logn), so we should consider about binary search, so how to apply binary search to find the low bound and high bound? We can make target -0.5 for searching low bound and target+0. 5 for the high bound. Be careful the corner case.

public class Solution {
    public int[] searchRange(int[] A, int target) {
		if(A==null||A.length==0)
			return null;
		int[] results={-1,-1};
		int low=binarySearch(A,target-0.5);
		if(low>=A.length||A[low]!=target)
			return results;
		results[0]=low;
		results[1]=binarySearch(A,target+0.5)-1;
		return results;
    }
	private int binarySearch(int[] A,double target){
		int low=0;
		int high=A.length-1;		
		while(low<=high){
			int mid=low+(high-low)/2;
			if(target==A[mid])
				return mid;
			if(target<A[mid])
				high=mid-1;
			else
				low=mid+1;
		}
		return low;
	}
}


2. Or

public class Solution {
    public int[] searchRange(int[] A, int target) {
        int[] results = {-1, -1};       
        int low=binarySearch(A,target);
        if (A[low] != target)
            return results; 		
		results[0] = low;	
		// Remember the "target+1"
        int high=binarySearch(A,target+1);		
		high = A[high] == target ? high : high - 1;
        results[1] = high;
        return results;
    }
	private int binarySearch(int[] A,int target){
		int low = 0;
        int high = A.length - 1;
        while (low < high) {
            int mid = low+(high - low) / 2;
            if (A[mid] < target)
                low = mid + 1;
            else
                high = mid;
        }
		return low;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章