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].
http://oj.leetcode.com/problems/search-for-a-range/
题意分析:二分搜索的一个变种,找到target存在的区间。
二分搜索,只不过分别搜索begin和end。
begin找到target时候,如果它的左边元素和它相等,并且它不是第一个元素,把end设为middle - 1,继续搜索。
end同理找到target的时候,如果它的右边元素和它相等,并且它不是第后一个元素,把begin设为middle + 1,继续搜索。
public class Solution { public int[] searchRange(int[] A, int target) { int [] result = {-1,-1}; int begin = 0; int end = A.length - 1; int middle = 0; //以下搜索是找最左边target的索引 while(begin<=end) { middle = begin + ((end - begin)>>1); if(A[middle]==target) { if((middle>=1&&A[middle-1]!=target)||middle==0) { result[0] = middle; break; } else { end = middle - 1; } } else { if(A[middle]>target) { end = middle - 1; } else { begin = middle + 1; } } }
begin = 0; end = A.length - 1; while(begin<=end) { middle = begin + ((end - begin)>>1); if(A[middle]==target) { if((middle<(A.length-1)&&A[middle+1]!=target)||middle==(A.length-1)) { result[1] = middle; break; } else { begin = middle + 1; } } else { if(A[middle]>target) { end = middle - 1; } else { begin = middle + 1; } } } return result; }}//以下搜索是找最右边target的索引