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

Example

Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

Solution:

 public class Solution {
/**
*@param A : an integer sorted array
*@param target : an integer to be inserted
*return : a list of length 2, [index1, index2]
*/
public ArrayList<Integer> searchRange(ArrayList<Integer> A, int target) {
ArrayList<Integer> res = new ArrayList<Integer>();
int start = -1, end = -1;
int p1 = 0, p2 = A.size()-1;
//find start point.
while (p1<=p2){
int mid = (p1+p2)/2; if (A.get(mid)==target){
if (mid==0 || A.get(mid-1)!=target){
start = mid;
break;
} else {
p2 = mid-1;
}
} else if (A.get(mid)>target)
p2 = mid-1;
else p1 = mid+1;
} //find end point.
p1 = 0;
p2 = A.size()-1;
while (p1<=p2){
int mid = (p1+p2)/2; if (A.get(mid)==target){
if (mid==A.size()-1 || A.get(mid+1)!=target){
end = mid;
break;
} else p1 = mid+1;
} else if (A.get(mid)>target)
p2 = mid-1;
else p1 = mid+1;
} res.add(start);
res.add(end); return res;
}
}
上一篇:Java数据类型和变量


下一篇:关于XCode工程中PrefixHead.pch文件的使用