代码随想录算法训练营第一天 | LeetCode:704. 二分查找 ,LeetCode:27 移除元素

701.二分查找

题目链接:https://leetcode.cn/problems/binary-search/description/

暂时没有深入研究边界条件(明天补),对于折半查找的代码,考研时复习过,上手写才发现掌握还是不牢靠。

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int low = 0;
        int high = nums.size() - 1;
        
        while(low <= high){
            int mid = (low + high) / 2;
            if(nums[mid] > target){
                high = mid - 1;
            }else if(nums[mid] < target){
                low = mid + 1;
            }else{
                return mid;
            }
        }
        return -1;
    }
};

 视频链接:https://www.bilibili.com/video/BV1fA4y1o715/

文章讲解:https://programmercarl.com/%E6%95%B0%E7%BB%84%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html

27. 移除元素 

 题目链接:https://leetcode.cn/problems/remove-element/description/

这道题我最开始外层用的while循环,与for循环相比,while还是更适合于链表,最致命的错误是在覆盖当前元素后,没有将i返回到当前元素前一个位置,若相连两个元素等于val,此时后一个覆盖前一个后,i++继续往后执行,就会将原来漏删val元素 。

暴力解:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int i = 0;
        int n = nums.size();
        for(i; i < n; i++){
            if(nums[i] == val){
                for(int j = i; j < n - 1; j++){
                    nums[j] = nums[j+1];//
                } 
                n--;
                i--;
            }
        }
        return n;
    }
};

双指针解:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        //快慢指针解法
        int fast,last = 0;
        for(fast = 0; fast < nums.size(); fast++){
            if(nums[fast] != val){
                nums[last] = nums[fast];
                last++;
            }
        }
        return last;
    }
};

这种解法真的很实用,核心就是越过要删去的元素,将原来数组中非val值元素插入到“新数组中”。

 文章链接:https://programmercarl.com/0027.%E7%A7%BB%E9%99%A4%E5%85%83%E7%B4%A0.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE

视频链接:https://www.bilibili.com/video/BV12A4y1Z7LP/

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值