704、二分查找
第一反应当然是调库啦~
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
auto it = lower_bound(nums.begin(), nums.end(), target);
if (it == nums.end()) return -1;
if (*it != target) return -1;
return it - nums.begin();
}
};
再手写下二分
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
int L = 0, R = n - 1;
while (L < R)
{
int mid = (L + R) >> 1;
if (nums[mid] == target) return mid;
if (nums[mid] < target) L = mid + 1;
else R = mid;
}
if (nums[L] == target) return L;
return -1;
}
};
27. 移除元素
前后双指针
// 双指针
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
int slow = 0, fast = 0;
while (fast < n)
{
if (nums[fast] != val) nums[slow++] = nums[fast];
fast ++;
}
return slow;
}
};