代码随想录算法训练营第一天

 今日刷题两道:数组理论基础,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循环的工作。

定义快慢指针

  • 快指针:寻找新数组的元素 ,新数组就是不含有目标元素的数组
  • 慢指针:指向更新 新数组下标的位置
 
posted @   要坚持刷题啊  阅读(110)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示