Given a sorted array of integers, find the starting and ending position of a given target value.
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:
1. 两次二分查找,先找第一个,再找最后一个
public ArrayList<Integer> searchRange(ArrayList<Integer> A, int target) {
ArrayList<Integer> result = new ArrayList<Integer> ();
if (A == null || A.size() == 0) {
result.add(-1);
result.add(-1);
return result;
}
int start = 0;
int end = A.size() - 1;
int mid;
while (start + 1 < end) {
mid = start + ((end - start) >> 1);
if (A.get(mid) == target) {
end = mid;
} else if (A.get(mid) > target) {
end = mid - 1;
} else {
start = mid + 1;
}
}
if (A.get(start) == target) {
result.add(start);
} else if (A.get(end) == target) {
result.add(end);
} else {
result.add(-1);
result.add(-1);
return result;
}
start = 0;
end = A.size() - 1;
while (start + 1 < end) {
mid = start + ((end - start) >> 1);
if (A.get(mid) == target) {
start = mid;
} else if (A.get(mid) > target) {
end = mid - 1;
} else {
start = mid + 1;
}
}
if (A.get(end) == target) {
result.add(end);
} else {
result.add(start);
}
return result;
}
2. 一次二分查找,先找第一个,然后依次向后查找
public ArrayList<Integer> searchRange(ArrayList<Integer> A, int target) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (A == null || A.size() == 0) {
result.add(-1);
result.add(-1);
return result;
}
int start = 0;
int end = A.size() - 1;
int mid;
while(start + 1 < end) {
mid = start + ((end - start) >> 1);
if(target <= A.get(mid)) {
end = mid;
} else {
start = mid;
}
}
// Find start
int range;
if(target == A.get(start)) {
range = start;
} else if(target == A.get(end)) {
range = end;
} else {
result.add(-1);
result.add(-1);
return result;
}
result.add(range);
// Find end
while((++range) < A.size()) {
if(target != A.get(range)) {
break;
}
}
result.add(range - 1);
return result;
}
如果重复数字多的话,两次二分查找会快。
如果重复数字少的话,一次二分查找会快。
思路:
用二分查找找到第一个满足条件的数,再找到最后一个满足条件的数。