方法:二分
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, r = nums.size()-1;
while (l <= r) {
int mid = l + r >> 1;
if (nums[mid] > target) r = mid-1;
else if (nums[mid] < target) l = mid + 1;
else return mid;
}
return -1;
}
};
时间复杂度O(), 空间复杂度O(1)
方法:二分
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n = nums.size();
int l = 0, r = n-1;
vector<int> res(2, -1);
if (!nums.size()) return res;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] >= target) r = mid;
else l = mid + 1;
}
if (nums[l] != target) return res;
else {
res[0] = l;
l = 0, r = n - 1;
while (l < r) {
int mid = l + r + 1 >> 1;
if (nums[mid] <= target) l = mid;
else r = mid - 1;
}
res[1] = l;
}
return res;
}
};
时间复杂度O(), 空间复杂度O(1)
方法:二分
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
int mid = l + r >> 1;
if (nums[mid] >= target) r = mid-1;
else l = mid + 1;
}
return l;
}
};
时间复杂度O(), 空间复杂度O(1)
方法:双指针
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int l, r;
for (l = 0, r = 0; l < nums.size(); ++l) if (nums[l] != val) nums[r++] = nums[l];
return r;
}
};
时间复杂度O(n), 空间复杂度O(1)
方法:暴力
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i, n = nums.size();
for (i = 0; i < n; ++i) {
if (nums[i] == val) {
for (int j = i + 1; j < n; ++j) {
nums[j-1] = nums[j];
}
--i;
--n;
}
}
return n;
}
};
时间复杂度O(), 空间复杂度O(1)