Find First and Last Position of Element in Sorted Array
Solution 1
由于问题要求中限制了时间复杂度,本题就是利用二分搜索的判断条件设置来控制指针的移动方向。以右指针为例判定条件为小于等于,多个连续相等目标元素将会导致偏左(右指针调整);如果判定条件为小于,则会导致偏右。但是实现中需要注意各种奇怪的边界条件……
- 时间复杂度: O ( log n ) O(\log n) O(logn),其中 n n n为输入序列长度,题目要求对数复杂度
- 空间复杂度: O ( 1 ) O(1) O(1),原位搜索,仅维护常数个状态变量
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans = {-1, -1};
int temp = binarySearch(nums, target, true);
if (temp == nums.size() || nums[temp] != target) {
return ans; // 元素不存在
}
else {
ans[0] = temp;
ans[1] = binarySearch(nums, target, false) - 1;
}
return ans;
}
private:
int binarySearch(vector<int>& nums, int target, bool isLeft) {
// cout << "Check!" << endl;
int left = 0, right = nums.size(); // 因为右移方案,指针会移到边界右侧,对单元素输入进行额外处理
int mid;
while (left < right) {
// cout << left << " " << right << endl;
mid = (left + right) / 2;
if (isLeft) {
if (nums[mid] >= target) {
right = mid;
}
else {
left = mid + 1;
}
}
else {
if (nums[mid] > target) {
right = mid;
}
else {
left = mid + 1;
}
}
}
return left;
}
};
Solution 2
Solution 1的Python实现
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
ans = [-1, -1]
temp = self.__binarySearch(nums, target, True)
if temp == len(nums) or nums[temp] != target: return ans
else:
ans[0] = temp
ans[1] = self.__binarySearch(nums, target, False) - 1
return ans
def __binarySearch(self, nums: List[int], target: int, isLeft: bool) -> int:
left, right = 0, len(nums)
while left < right:
mid = (left + right) // 2
if isLeft:
if nums[mid] >= target: right = mid
else: left = mid + 1
else:
if nums[mid] > target: right = mid
else: left = mid + 1
return left