您的位置:首页 > 其它

leetcode 96: Search for a Range

2013-03-03 18:07 441 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: