2024.1.22【数组】2.移除元素

2024.1.22【数组】2.移除元素

力扣 27.移除元素

  1. 函数erase():时间复杂度 O(n)
  2. 数组:元素在内存地址中是连续的,不能单独删除某个元素,只能 覆盖
解法1:暴力解法
//两层for循环,一个for循环遍历数组元素 ,第二个for循环更新数组
// 时间复杂度:O(n^2)
// 空间复杂度:O(1)
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int size = nums.size();
        for (int i = 0; i < size; i++) {
            if (nums[i] == val) { // 发现需要移除的元素,就将数组集体向前移动一位
                for (int j = i + 1; j < size; j++) {
                    nums[j - 1] = nums[j];
                }
                i--; // 因为下标i以后的数值都向前移动了一位,所以i也向前移动一位
                size--; // 此时数组的大小-1
            }
        }
        return size;
    }
};

解法2:双指针法(快慢指针法)
// 快指针:寻找新数组的元素 ,新数组就是不含有目标元素的数组
// 慢指针:指向更新 新数组下标的位置
// 时间复杂度:O(n)
// 空间复杂度:O(1)
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int slow = 0;
        for (int fast = 0; fast < nums.size(); fast++) {
            if (val != nums[fast]) {
                nums[slow] = nums[fast];
                slow ++;
            }
        }
        return slow; //slow 即新数组的长度
    }
};

练习1

力扣 26.删除有序数组中的重复项

//题目要求:原地修改;解法:双指针
//空间复杂度:O(n)
//空间复杂度:O(1)
   class Solution{
    public:
     int removeDuplicates(vector<int>& nums) {
        int index = 0;
        for (int i = 1; i < nums.size(); i++) {
            //找到不重复的元素,赋值到数组的开头
            if (nums[i] != nums[index]) {
                nums[++index] = nums[i];//index先自加1,再进行语句的赋值
            }
        }
        return index + 1;
    }
   };

官方答案:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int n = nums.size();
        if (n == 0) {
            return 0;
        }
        int fast = 1, slow = 1;
        while (fast < n) {
            if (nums[fast] != nums[fast - 1]) {
                nums[slow] = nums[fast];
                ++slow;
            }
            ++fast;
        }
        return slow;
    }
};

若采用暴力解法,时间复杂度O(n),空间复杂度O(n)

  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值