#172 Remove Element

本文介绍了一种使用双指针技巧快速移除数组中指定值的方法,并提供了一个高效的 C++ 实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Given an array and a value, remove all occurrences of that value in place and return the new length.

The order of elements can be changed, and the elements after the new length don't matter.

Example

Given an array [0,4,4,0,0,2,4,4]value=4

return 4 and front four elements of the array is [0,0,0,2]

题目思路:

这题还是用two pointer的做法,两个pointer:l和i的起始点都在数组开始。然后i一个一个往前挪动,如果A[i] != elem,就把A[l]赋值A[i],然后l往后挪一位。最后的长度就是l的值。

Mycode(AC = 15ms):

class Solution {
public:
    /** 
     *@param A: A list of integers
     *@param elem: An integer
     *@return: The new length after remove
     */
    int removeElement(vector<int> &A, int elem) {
        // write your code here
        if (A.size() == 0) return 0;
        
        int left = 0;
        for (int i = 0; i < A.size(); i++) {
            if (A[i] != elem) {
                A[left++] = A[i];
            }
        }
        
        return left;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值