代码随想录Day1 #207 #27

LeetCode704

讲解文档
视频讲解

LeetCode27

讲解文档
视频讲解

LeetCode704  Binary Search

class Solution {
public:
    int search(vector<int>& nums, int target) {
        const auto it = ranges :: lower_bound(nums, target);
        return (it == nums.cend() || *it != target) ? -1 : distance(nums.begin(), it);
    }
};
  • 时间复杂度:O(log n)
  • 空间复杂度:O(1)

自己做的时候没有太考虑区间哪边开哪边闭的问题, 看了解题方案之后才有些理解。

LeetCode27 Remove Element

  • 暴力解法
  • class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            int size = nums.size();
            for (int i = 0; i < size; i++){
                //if the current number is the target to be removed
                if (nums[i] == val){ 
                    //then move the whole array one step forward 
                    for (int j = i + 1; j < size; j++){
                        nums[j - 1] = nums[j];
                    }
                    i--;    //i move one place alongside the array
                    size--; //size of array -1
    
                }
            }
            return size;
        }
    };
  • 单指针(?)解法
  • class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            int i = 0;
    
            for (const int num : nums)
            if (num != val)
            nums[i++] = num;
    
            return i;
            
        }
    };

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值