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);
}
}
删除有序数组的重复项II
最新推荐文章于 2024-10-10 09:56:47 发布
该博客主要探讨了一个Java方法,用于移除整数数组中的重复元素并调整数组长度。`RemoveDuplicates`类中定义了`removeDuplicates`方法,通过两个指针i和j,遍历数组并删除连续重复项。当找到超过两个连续重复元素时,`remove`方法被调用来移除多余的元素并更新数组长度。示例中展示了如何处理包含多个重复值的数组。
摘要由CSDN通过智能技术生成