使用两个指针删除数组中的目标元素--索引越界



我正在尝试从数组中删除目标元素,如果输入是[3,3,2,3],而我的目标是3,我应该得到[2,2]。逻辑很简单,使用慢速和快速指针,如果我们需要复制,移动慢速指针,否则移动快速指针以跳过目标。

但我一直在获取超出范围的索引错误,不知道为什么?

public int[] removeElement(int[] input, int value) {
int slow = 0;
int fast = 0;
while (fast < input.length) {
while (input[fast] == value && fast < input.length) {
fast++;
}
input[slow++] = input[fast++];
}
return Arrays.copyOfRange(input, 0, slow);
}

发生了太多++。最好在调试器或纸上看到。最好不要在complexer表达式中使用++。

这并不奇怪,因为它可以做得更简单:

public int[] removeElement(int[] input, int value) {
int slow = 0;
int fast = 0;
while (fast < input.length) {
if (input[fast] != value) {
input[slow++] = input[fast];
} 
++fast;
}
return Arrays.copyOf(input, slow);
}

您的数组:[3,3,2,3,3]
第一个问题是:

while (input[fast] == value && fast < input.length) {
fast++;
}

最后一个索引是CCD_ 1并且小于其大小(6(->fast++->现在fast=6
现在在下一次迭代中,
input[6]==value将导致索引越界错误。

我认为您需要在两个输入后面加一个-1。长度

这是因为input.length以人类思考的方式返回大小(如果有一个条目,它会返回1(,但如果你与数组交谈,他们需要以计算机方式(从0开始(

像这样:

public static int[] removeElement(int[] input, int value) {
int slow = 0;
int fast = 0;
while (fast < input.length-1) {
while (input[fast] == value && fast < input.length-1) {
fast++;
}
input[slow++] = input[fast++];
}
return Arrays.copyOfRange(input, 0, slow);
}

最新更新