leetcode 96: Search for a Range

Search for a RangeMar 3 '12

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].

 

public class Solution {
    public int[] searchRange(int[] A, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int[] res = new int[2];
        res[0] = lowerbound(A,target);
        res[1] = upperbound(A,target);
        return res;
    }
    
    public static int upperbound(int[] num, int target){
		//find last 2,
		int low=0;
		int high=num.length - 1;
		int mid = low + (high-low+1)/2;
		
		while(low<high){
			mid = low + (high-low+1)/2;
			if(num[mid]<=target){
				low = mid;
			} else {
				high = mid - 1;
			}
		}
        return num[low] == target ? low : -1;
	}
	
	public static int lowerbound(int[] num, int target){
		//find first 2.
		int low=0;
		int high=num.length - 1;
		int mid = low + (high-low)/2;
		
		while(low<high) {
			mid = low + (high-low)/2;
			if(num[mid]>=target){
				high = mid;
			} else {
				low = mid + 1;
			}
		}
		return num[high] == target ? high : -1;
	}
}


 

posted @ 2013-03-03 18:07  西施豆腐渣  阅读(128)  评论(0编辑  收藏  举报