代码随想录算法训练营第一天 | 704.二分查找、35.搜索插入位置、27.移除元素
704.二分查找
题目链接
视频讲解
**二分查找需要注意的区间选择,个人认为左闭右闭的思路更简单。**
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
int mid;
while(left <= right) {
mid = (left + right) / 2;
cout << mid;
if(target > nums[mid]) {
left = mid + 1;
}
else if(target < nums[mid]) {
right = mid - 1;
}
else {
return mid;
}
}
return -1;
}
};
35.搜索插入位置
题目链接
讲解
**在二分查找的基础上,判断插入的位置,思考为何最后输出right+1。**
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
int mid;
while(left <= right) {
mid = (left + right) / 2;
if(nums[mid] < target) {
left = mid + 1;
}
else if(nums[mid] > target) {
right = mid - 1;
}
else {
return mid;
}
}
return right + 1;
}
};
27.移除元素
题目链接
讲解
**用到了双指针中的快慢指针,慢指针记录新的数组,快指针往下遍历。**
//暴力法
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int size = nums.size();
for(int i = 0; i < size; i++) {
if(nums[i] == val) {
for(int j = i + 1; j < size; j++) {
nums[j - 1] = nums[j];
}
size--;
i--;
}
}
return size;
}
};
//快慢指针
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slowIndex = 0;
for(int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
if(nums[fastIndex] != val) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};