Leetcode NO.27 Remove Element

本文介绍了一种使用双指针技术高效移除数组中特定值的方法,并提供了C++实现代码。该算法通过前后两个指针配合,实现了原地删除指定元素并返回新数组长度的功能。

本题要求如下:

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

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

这题是道简单题,而且也不是第一次做,所以很快就做出来了。。

代码:

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int ptr_i = 0;
        int ptr_j = n - 1;
        int len = n;
        while (ptr_i < len) {
            if (A[ptr_i] == elem) {
                swap(A[ptr_i], A[ptr_j--]);
                --len;
            }
            else
                ++ptr_i;
        }
        return len;
    }
};
用的是two pointer的方法,思路就是一个前指针,一个后指针,

对前指针遍历,如果遇到了elem,则和后指针指向的元素交换,同时,后指针往前移动,len减1

此时,需要对该元素再次检测,以防其也等于elem。


由于Leetcode改了function的接口,更新下代码

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int l = 0;
        int r = nums.size() - 1;
        while (l <= r) {
            if (nums[l] == val) {
                swap(nums[l], nums[r--]);
            }
            else {
                ++l;
            }
        }
        return l;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值