public class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = {-1, -1};
if (nums == null || nums.length < 1) {
return result;
}
int length = nums.length;
int left = 0;
int right = length - 1;
while (left + 1 < right) {
int mid = left + (right - left) / 2;
if (target > nums[mid]) {
left = mid;
} else {
right = mid;
}
}
if (nums[left] == target) {
result[0] = left;
} else if (nums[right] == target) {
result[0] = right;
} else {
return result;//no answer.
}
right = length - 1;
while ((left + 1) < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > target) {
right = mid;
} else {
left = mid;
}
}
if (nums[right] == target) {
result[1] = right;
} else {
result[1] = left;
}// if the program runs this code, it means that the input can find the target
return result;
}
}
本文介绍了一种在数组中查找指定元素的高效算法,通过二分查找优化搜索过程,确保在复杂数据集中的快速定位。
939

被折叠的 条评论
为什么被折叠?



