[LintCode/LeetCode] Remove Element [Two Pointers]

删除数组中特定值并返回新长度的高效算法
本文介绍了一种通过双指针法删除数组中特定值的算法,详细解释了双指针I和双指针II两种实现方式,并提供了相应的代码示例。该算法能够直接在原数组上进行操作,而不需要额外的空间,同时保持时间复杂度为O(n)。

Problem

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]

Note

双指针I:头指针i等于指定元素elem的时候,用尾指针j的值替换i的值(A[i] = A[--j]);否则头指针i继续向后走。
双指针II:i和j都作为头指针,当i的值不是指定元素elem的时候,将A[i]复制到j的位置;否则i继续向后走。最后返回j,就是所有非elem元素的数量。

Solution

1. 双指针I

public class Solution {
    public int removeElement(int[] A, int elem) {
        int i = 0, j = A.length;
        while (i < j) {
            if (A[i] == elem) {
                A[i] = A[--j];
            }
            else i++;
        }
        return j;
    }
}

2. 双指针II

public class Solution {
    public int removeElement(int[] A, int elem) {
        int i = 0, j = 0;
        while (i < A.length) {
            if (A[i] != elem) {
                A[j++] = A[i];
            }
            i++;
        }
        return j;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值