代码随想录算法训练营第一天
今日刷题两道:数组理论基础,704. 二分查找,27. 移除元素
**704. 二分查找
比较简单,但是要注意题目要求,左闭右闭,左闭右开,写法不一样。
class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0;
int high = nums.size()-1;
int mid;
while(low <= high){
mid = (low + high) / 2;
if(target == nums[mid])
return mid;
else if(target > nums[mid])
low = mid + 1;
else{
high = mid - 1;
}
}
return -1;
}
};
**27. 移除元素
题目链接:https://leetcode.cn/problems/remove-element/
文章讲解:https://programmercarl.com/0027.%E7%A7%BB%E9%99%A4%E5%85%83%E7%B4%A0.html
暴力解法,双层for循环,通过
class Solution { public: int removeElement(vector<int>& nums, int val) { int count = nums.size(); for(int i=0;i<count;i++){ if(nums[i]==val){ for(int j=i+1;j<count;j++){ nums[j-1]=nums[j]; } i--; count--; } } return count; } };
双指针法
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow=0;
for(int fast=0;fast<nums.size();fast++){
if(nums[fast]!=val){
nums[slow]=nums[fast];
slow++;
}
}
return slow;
}
};
双指针法(快慢指针法): 通过一个快指针和慢指针在一个for循环下完成两个for循环的工作。
定义快慢指针
- 快指针:寻找新数组的元素 ,新数组就是不含有目标元素的数组
- 慢指针:指向更新 新数组下标的位置
浙公网安备 33010602011771号