1089 Leetcode Duplicate Zeros: where is the bug?



提示:给定一个固定长度的整数数组,重复每次出现的零,将剩余元素向右移动。请注意,不会写入超出原始数组长度的元素。对输入数组执行上述修改,不要从函数中返回任何内容。

使用此输入:[8,4,5,0,0,7],预期输出:[8,45,0,0,0,0]我的解决方案返回:[8,8,4,5,0,0]

class Solution {
public void duplicateZeros(int[] arr) {
int possible_duplicates = 0;
//items remaining is total spaces - duplicate zero's
//first pass to determine number of zeros to duplicate
int arr_length = arr.length - 1;
for(int item = 0; item <= arr_length; item++) {
if (arr[item] == 0) {
//Edge case: no more space to duplicate zero
if(item == arr.length) {
//set the final index to 0 since it wont be duplicated just shifted down
arr[arr_length + possible_duplicates] = 0;
arr_length--;
break;
}
possible_duplicates++;
arr_length--;
}
}
//second pass to input new array, in place
//from the last element of the new array, shift towards right based on duplicate count
for (int i = arr_length; i >= 0; i--){
if (arr[i] == 0){
arr[i + possible_duplicates] = 0;
possible_duplicates--;
arr[i + possible_duplicates] = 0;
} else {
arr[i + possible_duplicates] = arr[i];
}
}
}
}

我想您已经意识到,您的问题是应该保留一个0,但没有复制的空间。您正试图在第一次传递中的内部if语句中满足这种边缘情况。

//Edge case: no more space to duplicate zero
if(item == arr.length) {

一旦到达第5项,即第三个0和由于空间不足而无法复制的0,arr.length将保留为-8,即数组的固定长度。所以你没有进入你内心的if语句。这种情况永远不可能是真的。我认为这只是一个拼写错误,我认为你可以自己修复,所以我现在不会破坏它。(一旦你发现了,我可以在这里添加它,以防其他读者好奇。(

编辑:作为解决方案,我正在粘贴您自己的评论:

谢谢你,是的,你是对的,所需要的只是调整arr.lengtharr_length

一个可能的结论是arr_length不是一个好的变量名,因为它让人想起了arr.length,而且不一样。我理解你为什么不想要indesToLastItemToRetain,因为它很长,但也许你可以想点什么。

我同意Henry Twist的评论:学习使用调试器会对你很有帮助。

顺便说一句,这是你精心设计的算法。

最新更新