import java.util.Arrays;
public class Solution {
//解法1
public int[] searchRange(int[] nums, int target) {
if (nums == null || nums.length == 0)
return new int[]{-1, -1};
int i = 0;
int j = nums.length - 1;
int start = -1, end = -1;
int mid;
while (i < j) {
mid = (i + j) / 2;
if (target <= nums[mid]) {
j = mid;
} else {
i = mid + 1;
}
}
if (nums[i] == target) {
start = i;
} else {
return new int[]{-1, -1};
}
j = nums.length - 1;
while (i < j) {
mid = (i + j + 1) / 2;
if (target >= nums[mid]) {
i = mid;
} else {
j = mid - 1;
}
}
if (nums[i] == target) {
end = i;
}
return new int[]{start, end};
}
//解法2
public int[] searchRange2(int[] nums, int target) {
if (nums == null || nums.length == 0)
return new int[]{-1, -1};
int start = lowerBound(nums, target);
if (start >= 0 && start < nums.length && nums[start] == target)
return new int[]{start, lowerBound(nums, target + 1) - 1};
return new int[]{-1, -1};
}
public int lowerBound(int[] nums, int target) {
int i = 0;
int j = nums.length;
int mid;
while (i < j) {
mid = (i + j) / 2;
if (target <= nums[mid]) {
j = mid;
} else {
i = mid + 1;
}
}
return i;
}
public static void main(String[] args) {
int[] nums = {5, 7, 7, 8, 8, 10};
int target = 8;
System.out.println(Arrays.toString(new Solution().searchRange(nums, target)));
}
}
二分查找排序数组中指定数所在区间
最新推荐文章于 2024-08-17 20:04:47 发布