java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.csdn.net/grd_java/article/details/123063846 |
---|
二分查找
解题思路:时间复杂度O(
l
o
g
2
n
log_2n
log2n),空间复杂度O(
1
1
1) |
---|
- 进行两遍二分查找,第一次先找到最左边的target
- 第二次找最右边的target
class Solution {
public int[] searchRange(int[] nums, int target) {
int lowerPos = findPos(nums, target, true);
if (-1 == lowerPos) return new int[] {-1, -1};
int higherPos = findPos(nums, target, false);
return new int[] {lowerPos, higherPos};
}
public int findPos(int[] nums, int target, boolean findLower) {
int left = 0, right = nums.length -1, targetPos = -1;
while (left <= right) {
int pos = left + ((right - left) >> 1);
if (nums[pos] > target) right = pos - 1;
else if (nums[pos] < target) left = pos + 1;
else {
if (findLower) {
right = pos - 1;
} else left = pos + 1;
targetPos = pos;
}
}
return targetPos;
}
}