删除有序数组的重复项II

该博客主要探讨了一个Java方法,用于移除整数数组中的重复元素并调整数组长度。`RemoveDuplicates`类中定义了`removeDuplicates`方法,通过两个指针i和j,遍历数组并删除连续重复项。当找到超过两个连续重复元素时,`remove`方法被调用来移除多余的元素并更新数组长度。示例中展示了如何处理包含多个重复值的数组。
摘要由CSDN通过智能技术生成
public class RemoveDuplicates {
    public int removeDuplicates(int[] nums) {
        int i = 0;
        int j = 0;
        int length = nums.length;
        while (i < length) {
            while (j < length && nums[j] == nums[i]) {
                j++;
            }
            if (j - i > 2) {
                remove(nums, j, length, j - i - 2);
                length = length - j + i + 2;
                j = i + 2;
                continue;
            }
            i = j;

        }
        return length;
    }
    public void remove(int[] nums, int j, int length, int removeNum) {

        while (j < length) {
            nums[j - removeNum] = nums[j];
            j++;
        }
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1,1,1,2,2,2,3,3};
        RemoveDuplicates rd = new RemoveDuplicates();
        rd.removeDuplicates(nums);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值