题目地址:
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
求长 n n n数组 a a a中出现的第一个和最后一个 x x x的下标。如果不存在则返回两个 − 1 -1 −1。
寻找数组从左到右第一个大于等于
x
x
x的数,接着寻找从左到右最后一个小于等于
x
x
x的数。如果找不到,就返回{-1, -1}
。可以用二分法。代码如下:
class Solution {
public:
vector<int> searchRange(vector<int>& a, int x) {
int l = 0, r = (int)a.size() - 1;
if (l > r) return {-1, -1};
while (l < r) {
int mid = l + (r - l >> 1);
if (a[mid] >= x)
r = mid;
else
l = mid + 1;
}
if (a[l] != x) return {-1, -1};
vector<int> res{l};
r = (int)a.size() - 1;
while (l < r) {
int mid = l + (r - l + 1 >> 1);
if (a[mid] <= x)
l = mid;
else
r = mid - 1;
}
res.push_back(l);
return res;
}
};
时间复杂度 O ( log n ) O(\log n) O(logn),空间 O ( 1 ) O(1) O(1)。