代码随想录算法训练营第一天
今日刷题两道:数组理论基础,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循环的工作。
定义快慢指针
- 快指针:寻找新数组的元素 ,新数组就是不含有目标元素的数组
- 慢指针:指向更新 新数组下标的位置
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构