首页 > 其他 > 详细

[LeetCode 34] Search for a Range

时间:2015-03-25 12:18:38      阅读:114      评论:0      收藏:0      [点我收藏+]

题目链接: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].
 *
 */

public class SearchForARange {

//	81 / 81 test cases passed.
//	Status: Accepted
//	Runtime: 210 ms
//	Submitted: 0 minutes ago

	
	public int low = Integer.MAX_VALUE;
	public int high = -1;
    public int[] searchRange(int[] A, int target) {
    	
    	searchRange(A, 0, A.length - 1, target);
    	
    	if(low != Integer.MAX_VALUE)
    		return new int[]{low, high};
    	else 
    		return new int[]{-1, -1};
    }
    
    //二分法查找
    public void searchRange(int[] A, int left, int right, int target) {
    	if(left <= right) {
    		int mid = (left + right) / 2;
    		if(A[mid] < target) {
    			searchRange(A, mid + 1, right, target);
    		} else if (A[mid] > target) {
    			searchRange(A, left, mid - 1, target);
    		} else {
				low = Math.min(low, mid);
				high = Math.max(high, mid);
				searchRange(A, left, mid - 1, target);
				searchRange(A, mid + 1, right, target);
			}
    	}
    }
	public static void main(String[] args) {

	}

}


[LeetCode 34] Search for a Range

原文:http://blog.csdn.net/ever223/article/details/44618307

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!