随笔 - 12  文章 - 0  评论 - 0  阅读 - 444

移除数组元素

移除数组元素

移除数组元素主要有两种情况,一种是移除单个元素,另一种是移除多个元素。

这里讨论的情形为,移除的元素为数组中可能存在重复的某个元素

对应题目27. 移除元素💫

移除单个元素

移除单个元素,我们通常会想得到将此元素之后的元素前移从而完成元素的移除操作。这样做的时间复杂度为O(n),考虑到还有查找元素的时间开销,这里不仔细研究,所以最后的时间复杂度肯定大于O(n)。这里没有考虑末尾元素。

// assume the index of the element to be removed is j
for (int i = j;i < nums.size() - 1;i ++) {
	nums[i] = nums[i + 1];
}

另一种方式是,采用数组拷贝,将要移除的元素之后的子数组覆盖掉前面的元素,这种方式需要用到数组拷贝函数memcpy(),或者直接使用vector中的erase()函数。这两种方式的时间复杂度会小很多

移除多个元素

**这里运用到了快慢指针。快指针的作用是遍历整个数组元素,将非目标元素传给慢指针所指的位置,遇到目标元素则跳过。慢指针的作用则是将非目标元素保存,并记录其余元素的个数。由于只用到了一次循环,因此这个算法的时间复杂度为O(n),又因只在数组上面进行操作,只定义了两个指针,所以空间复杂度为O(1)

int removeElement(vector<int>& nums, int val) {
        // define a fast pointer and a slow pointer
        int fastPointer = 0,slowPointer = 0;
        for (;fastPointer < nums.size();fastPointer ++) {
            /* if the element pointed by the fast pointer is not equal to the val,
            ** then let this element cover the palce pointed by the slow pointer.
            ** if yes,fast pointer just skip it and slow pointer do nothing.
            */
            if (nums[fastPointer] != val) {
                nums[slowPointer] = nums[fastPointer];
                slowPointer ++;
            }
        }
        return slowPointer;
    }
posted on   Coeleone  阅读(96)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示